Peter Peter - 1 year ago 79
C# Question

Create and initialize dictionary from list

Is there a way to combine below two statements into one, so you can create and initialize a dictionary from an array in one single statement?

var myDictionary = new Dictionary<int, string>();
myList.ForEach(i => myDictionary.Add(i.property1, i.property2));

(whether or not that makes the code easier to read is another topic :-))

Answer Source

The Enumerable class has a nice class extension for the IEnumerable<>: Try

var myDictionary = myList.ToDictionary(key => key.property1, value => value.property2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download