Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีเพิ่มค่าสตริงเข้าไปใน C# List

ใช้เมธอด Add() เพื่อเพิ่มค่าสตริงเข้าไปใน List

ขั้นตอน

  1. ประกาศ List ของสตริง
  2. ใช้ Add() เพิ่มรายการ
List<string> myList = new List<string>();
myList.Add("Jack");
myList.Add("Ben");
myList.Add("Eon");
myList.Add("Tim");

โค้ดตัวอย่างเต็ม

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Demo
{
    public class Program
    {
        public static void Main(String[] args)
        {
            List<string> myList = new List<string>();
            myList.Add("Jack");
            myList.Add("Ben");
            myList.Add("Eon");
            myList.Add("Tim");
            
            Console.WriteLine("Count: " + myList.Count);
            
            // แสดงสมาชิกทั้งหมด
            foreach (string name in myList)
            {
                Console.WriteLine(name);
            }
        }
    }
}

ผลลัพธ์

Count: 4
Jack
Ben
Eon
Tim