[LINQ] List泛型 轉 ToDictionary 泛型

  • 34010
  • 0
  • LINQ
  • 2021-07-18

[LINQ] List泛型 轉 ToDictionary泛型

隨手記,假設有以下類別

class Member
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
} 

 

初始化

private void Form1_Load(object sender, EventArgs e)
{
    this._memberList = new List<Member>() 
    { 
        new Member(){Name="Yao",Age=18,Address="火星"},
        new Member(){Name="GG",Age=20,Address="地球"}
    };
} 

轉成ToDictionary<string,Member>

 

Dictionary<string, Member> dictionary = this._memberList.ToDictionary(data => data.Name);
foreach (var item in dictionary)
{
    this.listBox1.Items.Add(item.Key);
}
image

 

 

轉成ToDictionary<string,string>

 

Dictionary<string, string> dictionary = this._memberList.ToDictionary(data => data.Name, data => data.Address);
foreach (var item in dictionary)
{
    this.listBox1.Items.Add(item.Key);
}

 

image

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo