这个问题令人困惑,但如下面的代码所述,它更加清晰:
List<List<T>> listOfList;
// add three lists of List<T> to listOfList, for example
/* listOfList = new {
{ 1, 2, 3}, // list 1 of 1, 3, and 3
{ 4, 5, 6}, // list 2
{ 7, 8, 9} // list 3
};
*/
List<T> list = null;
// how to merger all the items in listOfList to list?
// { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // one list
// list = ???
不确定是否可以使用C#LINQ或Lambda?
基本上,我如何连接或“展平”列表列表?
答案 0 :(得分:385)
使用SelectMany扩展方法
list = listOfList.SelectMany(x => x).ToList();
答案 1 :(得分:11)
你是说这个吗?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
结果:9 9 9 1 2 3 4 5 6
答案 2 :(得分:11)
这是C#集成语法版本:
var items =
from list in listOfList
from item in list
select item;
答案 3 :(得分:1)
对于public static <T> boolean equalIgnoreOrder(Collection<T> c1, Collection<T> c2) {
int size1 = c1.size(); // O(1) for most implementations, but we cache for the exceptions.
if (size1 != c2.size()) {
return false;
}
Set<T> set;
Collection<T> other;
if (c1 instanceof Set) {
set = (Set<T>) c1;
other = c2;
} else if (c2 instanceof Set) {
set = (Set<T>) c2;
other = c1;
} else if (size1 < 12 ) { // N^2 operation OK for small N
return c1.containsAll(c2);
} else {
set = new HashSet<>(c1);
other = c2;
}
return set.containsAll(other); // O(N) for sets
}
等,使用
List<List<List<x>>>
此内容已发表在评论中,但我认为确实需要单独答复。