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

AddRange Method ใน C# List (เพิ่มหลายรายการพร้อมกัน)

AddRange() เพิ่ม Collection ทั้งชุดเข้าไปใน List พร้อมกัน

ตัวอย่าง

  1. สร้าง List และเพิ่มข้อมูล:
    List<int> list = new List<int>();
    list.Add(100); list.Add(200); list.Add(300); list.Add(400);
  2. สร้าง Array ข้อมูลใหม่:
    int[] arr = new int[4] { 500, 600, 700, 800 };
  3. ใช้ AddRange:
    list.AddRange(arr);

โค้ดสมบูรณ์

using System;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        List<int> list = new List<int>();
        list.Add(100); list.Add(200); list.Add(300); list.Add(400);
        int[] arr = new int[4] { 500, 600, 700, 800 };
        list.AddRange(arr);
        foreach (int val in list) Console.WriteLine(val);
    }
}