Peter Peter - 1 month ago 4
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 :-))


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

var myDictionary = myList.ToDictionary(key => key.property1, value => value.property2);