在 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/