Enumerable 中的 ToDictionary 方法

  • 975
  • 0
  • 2016-03-02

摘要:Enumerable 中的 ToDictionary 方法

今天在處理 Linq Join 的時候, 意外發現了一個好東西,

那就是 Enumerable 中的 ToDictionary 方法, 可以將 Enumerable 轉換成 Dictionary:


//設計一類別如下
class Person
{
    public int ID { get; set; }
    public string Name{ get; set; }
}

//宣告一個List
List<Person> family =
    new List<Person>
        { new Person{ ID = 1, Name = "Ita Tsai" },
          new Person{ ID = 2, Name = "Gin Lin" } };

//當我們想使用 ID 做為 Key, 則使用
Dictionary<int, Person>dictionary =
    family.ToDictionary(p => p.ID);

//方法預設 Value 為整個 Person 物件, 若想要進一步指定 Value, 則使用
Dictionary<int, string>dictionary =
    family.ToDictionary(p => p.ID, p => p.Name);

同樣的, 不只是List, 只要是有實作 IEnumerable 的類別, 都可以使用 ToDictionary 方法,

也可以使用在 Linq 的 Join 上。