C# 如何从子字典中获取子元素列表?

C# 如何从子字典中获取子元素列表?,c#,list,dictionary,C#,List,Dictionary,我想从子字典中获取子元素列表 我有这个: Dictionary<string, Dictionary<string, List<InstanceLog>>> dic; dic; 我想要这样的东西(从一个大列表中的子目录中获取所有InstanceLog列表): List logList=GetValues(dic); 我尝试过类似的方法,但不起作用: List<InstanceLog> logList = GetFetchtedList()

我想从子字典中获取子元素列表

我有这个:

Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;
dic;
我想要这样的东西(从一个大列表中的子目录中获取所有InstanceLog列表):

List logList=GetValues(dic);
我尝试过类似的方法,但不起作用:

List<InstanceLog> logList = GetFetchtedList()
  .Select(x => x.Value.ToList())
  .Cast<InstanceLog>()
  .ToList()
List logList=GetFetchtedList()
.Select(x=>x.Value.ToList())
.Cast()
托利斯先生()

非常感谢你的帮助

在技术语言中,您希望将存储在字典值中的列表展平,因此需要
选择many

var values = dic.Values
                 .SelectMany(val => val.Values)
                 .SelectMany(val => val);
其中,
将是类型为
IEnumerable
的数据的集合,这正是您想要的。

您必须将
dic
展平两次:

字典dic=。。。; 列表日志列表=dic .SelectMany(pair=>pair.Value)//内部字典 .SelectMany(pair=>pair.Value)//内部列表 .ToList();//具体化为一个大列表
SelectMany
是关键字。如果select是某种类型的集合,那么它所做的就是将其分组为一个列表。如果您喜欢,请按您的意愿返回
Union

Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;

var instanceLogs = dic.SelectMany(d => d.Value.Select(subd => subd.Value)).ToList();
dic;
var instanceLogs=dic.SelectMany(d=>d.Value.Select(subd=>subd.Value)).ToList();
dic上的
SelectMany
告诉linq:

“嘿,我将在这些括号内有一个集合结果,因此将它们分组为1个集合”

子词典上的
Select
仅返回集合1,供
SelectMany
抓取和处理


这将只迭代集合一次,并且不使用任何不需要的额外操作(linq方面)

请尝试selectmany()@the.Doc谢谢您的tipp使其不起作用。我得到以下信息:System.InvalidCastException:“无法将类型为”System.Collections.Generic.KeyValuePair
2[System.String,System.Collections.Generic.List
1[Models.InstanceLog]]”的对象强制转换为类型“模型”。InstanceLog。'出于兴趣,为什么要播放<代码>呢
?你能检查一下我的答案吗?这对你不管用吗?我在运行中编写了它,并试图在一行中尽可能地简化。这不是他“确切希望”的内容。你返回一个
KeyValuePair
,而不是
列表,你不必两次展平。这意味着您要迭代集合两次。你可以做一次。@Franck:当然,我们不必对任何(子)集合重复多次。我的意思是我们必须应用Falten操作-
SelectMany
-两次。对不起,我的措辞选择和可能的混乱
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
Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;

var instanceLogs = dic.SelectMany(d => d.Value.Select(subd => subd.Value)).ToList();