'List of objects to List of Lists in C#
I have a List of objects, say
List<MyObject> = new List<MyObject>{object1, object2, ..., object10}
Each object has property "Property1" which is a dictionary with different number of keys for each object, where for each key, the value is again a dictionary but here the value for each key is a string. I would like to convert this List<object> to List<List<string>>, so for each object I want to create a list with string values, where values are taken from this nested dictionary.
Solution 1:[1]
I think it's this:
yourList.Select(mo => mo.Property1.SelectMany(d => d.Value.Values).ToList()).ToList();
It produces a List<List<string>> - i'll use bold and italic to distinguish:
yourList.Selectproduces the enuemration that will become the List, so there is one entry in the List for every entry in the list ofMyObjectmo.Property1.SelectManyenumerates the outer dictionary ofProperty1, getting theValue.Valuesfor each entry in the outer dictionary.- Each outer entry's
Valueis the innerDictionary<...,string>and hence is a Dictionary with aValuescollection that is a bunch of strings.Value.Valuesthus represents a collection of strings associated with each outer dictionary entry - Fed with these multiple "collection of strings"
SelectManycollapses them into a single enumeration of strings, that is converted the a list with ToList, thus the.ToList()onSelectMany()gives you the List
- Each outer entry's
- The
.ToList()at the end of the expression gives you the List< ... >
Solution 2:[2]
The fast way to map it again:
var newList = new List<List<string>>();
foreach(var item in items){
newList.Add(item.Property1.Values.ToList<string>());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Meir |
