Phương thức ToDictionary là một phương thức mở rộng trong C # và chuyển đổi một tập hợp thành Từ điển.
Đầu tiên, tạo một mảng chuỗi -
string[] str = new string[] {"Car", "Bus", "Bicycle"}; Bây giờ, hãy sử dụng phương thức Từ điển để chuyển đổi một bộ sưu tập thành Từ điển -
str.ToDictionary(item => item, item => true);
Đây là mã hoàn chỉnh -
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
string[] str = new string[] {"Car", "Bus", "Bicycle"};
// key and value under ToDictionary
var d = str.ToDictionary(item => item, item => true);
foreach (var ele in d) {
Console.WriteLine("{0}, {1}", ele.Key, ele.Value);
}
}
} Đầu ra
Car, True Bus, True Bicycle, True