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

Phương thức ToDictionary trong C#

ToDictionary (LINQ) chuyển đổi sequence thành Dictionary<TKey, TValue> bằng cách chỉ định selector cho key và value.

Ví dụ

using System;
using System.Collections.Generic;
using System.Linq;

class Demo
{
    static void Main()
    {
        string[] str = { "Car", "Bus", "Bicycle" };
        var d = str.ToDictionary(item => item, item => true);

        foreach (var ele in d)
            Console.WriteLine("{0}, {1}", ele.Key, ele.Value);
    }
}

Kết quả

Car, True
Bus, True
Bicycle, True

Lưu ý: Key phải duy nhất, ném exception nếu trùng. Dùng ToLookup cho key trùng lặp.