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

Khởi tạo tập hợp (Collection Initialization) trong C#

C# cho phép khởi tạo tập hợp (collection initialization) bằng cú pháp ngắn gọn sử dụng dấu ngoặc nhọn { }, tương tự như khởi tạo đối tượng. Điều này làm cho code ngắn gọn, dễ đọc hơn so với việc gọi Add() nhiều lần.

Ví dụ với List<Employee>

var emp1 = new Employee() { EID = 001, EmpName = "Tim", EmpDept = "Finance" };
var emp2 = new Employee() { EID = 002, EmpName = "Tom", EmpDept = "HR" };

IList empDetails = new List { emp1, emp2 };

Mã nguồn hoàn chỉnh

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        var emp1 = new Employee() { EID = 001, EmpName = "Tim", EmpDept = "Finance" };
        var emp2 = new Employee() { EID = 002, EmpName = "Tom", EmpDept = "HR" };
        IList empDetails = new List { emp1, emp2 };
        
        Console.WriteLine("Nhân viên 1:");
        Console.WriteLine(emp1.EID);
        Console.WriteLine(emp1.EmpName);
        Console.WriteLine(emp1.EmpDept);
        
        Console.WriteLine("\nNhân viên 2:");
        Console.WriteLine(emp2.EID);
        Console.WriteLine(emp2.EmpName);
        Console.WriteLine(emp2.EmpDept);
    }
}

public class Employee
{
    public int EID { get; set; }
    public string EmpName { get; set; }
    public string EmpDept { get; set; }
}

Kết quả

Nhân viên 1:
1
Tim
Finance

Nhân viên 2:
2
Tom
HR

Các dạng khởi tạo tập hợp

LoạiVí dụ
Listnew List { 1, 2, 3 }
Dictionarynew Dictionary { {1, "A"}, {2, "B"} }
HashSetnew HashSet { 1, 2, 3 }
Arraynew int[] { 1, 2, 3 } hoặc new[] { 1, 2, 3 }
Queue/Stacknew Queue(new[] { 1, 2, 3 }) (cần constructor)

Lưu ý

  • Yêu cầu tập hợp implement IEnumerable và có phương thức Add.
  • Dictionary dùng cặp ngoặc nhọn lồng nhau cho key-value.
  • Có thể kết hợp với object initializer: new List { new Employee { Name = "A" } }.