How to insert values into C# Dictionary on instantiation?

后端 未结 8 1181
刺人心
刺人心 2021-02-01 00:12

Does anyone know if there is a way I can insert values into a C# Dictionary when I create it? I can, but don\'t want to, do dict.Add(int, \"string\") for each item

8条回答
  •  情歌与酒
    2021-02-01 00:26

    You can also use Lambda expressions to insert any Key Value pairs from any other IEnumerable object. Key and value can be any type you want.

    Dictionary newDictionary = 
                     SomeList.ToDictionary(k => k.ID, v => v.Name);
    

    I find that much simpler since you use the IEnumerable objects everywhere in .NET

    Hope that helps!!!

    Tad.

提交回复
热议问题