I want to get a list of subelements from a subdictionary
I have this:
Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;
And I want something like this (Fetch all InstanceLog-Lists from the subdictinary in one big list.):
List<InstanceLog> logList = GetValues(dic);
I have tried something like this but it don't work:
List<InstanceLog> logList = GetFetchtedList()
.Select(x => x.Value.ToList())
.Cast<InstanceLog>()
.ToList()
Thanks a lot for the help!
答案 0 :(得分:3)
您必须展平 dic
两次:
Dictionary<string, Dictionary<string, List<InstanceLog>>> dic = ...;
List<InstanceLog> logList = dic
.SelectMany(pair => pair.Value) // Inner Dictionaries
.SelectMany(pair => pair.Value) // Inner Lists
.ToList(); // Materialized as one big list
答案 1 :(得分:1)
以技术用语,您想拼合存储在字典值中的列表,因此您需要SelectMany
:
var values = dic.Values
.SelectMany(val => val.Values)
.SelectMany(val => val);
其中values
将是您所需要的IEnumerable<InstanceLog>
类型数据的集合。
答案 2 :(得分:0)
SelectMany
是关键字。如果选择是某种形式的集合,它将作为一个列表分组。如果您希望它像返回Union
一样返回。
Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;
var instanceLogs = dic.SelectMany(d => d.Value.Select(subd => subd.Value)).ToList();
SelectMany
上的dic
告诉linq:
“嘿,我将在这些括号内找到一个收集结果,因此将它们归为1个收集”
子词典上的Select
仅返回集合1,供SelectMany
抓取并处理。
此操作仅迭代一次,并且不使用任何不需要的额外操作(明智的选择)