Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức AddRange trong List C#

AddRange thêm toàn bộ collection phần tử vào List.

Khởi tạo List và thêm phần tử:

List<int> list = new List<int>();
list.Add(100); list.Add(200); list.Add(300); list.Add(400);

Tạo mảng để thêm vào List:

int[] arr = new int[4];
arr[0] = 500; arr[1] = 600; arr[2] = 700; arr[3] = 800;

Dùng AddRange() thêm toàn bộ mảng:

list.AddRange(arr);

Ví dụ hoàn chỉnh

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);
    }
}