Monday, March 18, 2019

Get dictionary object from list


When you get dictionary object from a list in C#, make sure that you select distinct values for the dictionary key. Otherwise the compiler will throw run time error if there are duplicates.

lst.GroupBy(x=>x.id).Select(x=>x.First()).ToDictionary(r => r.id, k => k.enabled);

Here is an example of how to select distinct keys from list and to return them in dictionary object.


No comments: