[英]List of objects to List of Lists in C#
I have a List
of objects, say List<MyObject> = new List<MyObject>{object1, object2, ..., object10}
我有一个对象List
,比如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
.每个对象都有属性“Property1”,它是一个字典,每个对象有不同数量的键,其中每个键的值也是一个字典,但这里每个键的值是一个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.我想将此List<object>
转换为List<List<string>>
,因此对于每个对象,我想创建一个包含字符串值的列表,其中值取自该嵌套字典。
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>());
}
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:它产生一个List < List <string>> - 我将使用粗体和斜体来区分:
yourList.Select
produces the enuemration that will become the List , so there is one entry in the List for every entry in the list of MyObject
yourList.Select
生成将成为List的枚举,因此对于MyObject
列表中的每个条目, List中都有一个条目mo.Property1.SelectMany
enumerates the outer dictionary of Property1
, getting the Value.Values
for each entry in the outer dictionary. mo.Property1.SelectMany
枚举Property1
的外部字典,获取外部字典中每个条目的Value.Values
。
Value
is the inner Dictionary<...,string>
and hence is a Dictionary with a Values
collection that is a bunch of strings.每个外部条目的Value
是内部Dictionary<...,string>
,因此是一个 Dictionary ,其Values
集合是一堆字符串。 Value.Values
thus represents a collection of strings associated with each outer dictionary entry因此, Value.Values
表示与每个外部字典条目相关联的字符串集合SelectMany
collapses them into a single enumeration of strings, that is converted the a list with ToList, thus the .ToList()
on SelectMany()
gives you the List使用这些多个“字符串集合” SelectMany
将它们折叠成单个字符串枚举,即使用 ToList 转换一个列表,因此SelectMany()
.ToList()
) 为您提供列表.ToList()
at the end of the expression gives you the List < ... >表达式末尾的.ToList()
为您提供List < ... >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.