c# - 如何从多个 List<> 中获取所有元素?

标签 c# linq c#-3.0 linq-to-objects

在 C# 中,我有以下类型:

List<List<mytype>> MyLists;
List<mytype> MainList;

我想将 MyList 中所有 List<> 中的每个元素放入 MainList 中。然后 MainList 将只有由 MyList 的每个 List<> 中的所有元素组成的元素。我已尝试以下操作,但收到有关无法推断类型的错误消息:

MyLists.ForEach(list => MainList.AddRange(list.SelectMany(x => x != null)));

我不确定要在 SelectMany() 中放入什么,因为我想要 List<> 中的所有元素。这些元素不需要满足任何条件。

有什么建议吗?

最佳答案

MainList.AddRange(from list in MyLists
                  from element in list
                  select element);

或者,如果你愿意,

MainList.AddRange(MyLists.SelectMany(list => list));

关于c# - 如何从多个 List<> 中获取所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7473806/

相关文章:

c# - 如何避免 linq 查询 C# 中的两个嵌入式循环

mysql - SQL order by < linq to entity framework 中的字符串

c# - Distinct 在 Entity Framework 上不起作用

c# - 参数类型 'void' 不可分配给参数类型 'System.Action'

c#-3.0 - 如何将字符串转换为 ushort 数组

c# - Entity Framework Core 上同一个表的两个一对一关系

c# - Visual Studio : When and why a class file name change will automatically update references to that class

c# - 为什么 TreeView 控件不绑定(bind)

c# - 从 F# 调用 C# 函数

c# - 如何使用接口(interface)和/或抽象类正确执行 MULTIPLE "mixins"