Ngôn ngữ LINQ - Toán tử ToDictionary
Phương thức ToDictionary trong LINQ
Phương thức ToDictionary chuyển đổi một đối tượng nguồn thành kiểu Dictionary. ToDictionary là một toán tử To.
Toán tử To bắt buộc thực hiện các truy vấn. Nó buộc trình cung cấp truy vấn từ xa (remote query provider) thực hiện truy vấn và nhận kết quả từ nguồn dữ liệu - ví dụ: cơ sở dữ liệu SQL Server.
Ví dụ minh họa phương thức ToDictionary với tập hợp có kiểu dữ liệu nguyên thủy:
IList<Student> studentList = new List<Student>()
{
new Student() { StudentID = 1, StudentName = "John", Age = 18 },
new Student() { StudentID = 2, StudentName = "Steve", Age = 21 },
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 },
new Student() { StudentID = 4, StudentName = "Ram", Age = 21 },
new Student() { StudentID = 5, StudentName = "Ron", Age = 21 }
};
//following converts list into dictionary where StudentId is a key
var studentDict = studentList.ToDictionary<Student, int>(s => s.StudentID);
foreach(var item in studentDict)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key,
item.Value.StudentName);
}
Đây là kết quả khi biên dịch và thực thi chương trình:
Key: 1, Value: John
Key: 2, Value: Steve
Key: 3, Value: Bill
Key: 4, Value: Ram
Key: 5, Value: Ron
Hình dưới đây cho thấy studentDict trong ví dụ trên chứa cặp khóa-giá trị, trong đó khóa là StudentID và giá trị là đối tượng Student.