在 C# 中将 List<List<T>> 转换为 List<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/462879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert List<List<T>> into List<T> in C#
提问by user57230
I have a List<List<int>>
. I would like to convert it into a List<int>
where each int is unique. I was wondering if anyone had an elegant solution to this using LINQ.
我有一个List<List<int>>
. 我想将其转换为List<int>
每个 int 都是唯一的。我想知道是否有人使用 LINQ 对此有一个优雅的解决方案。
I would like to be able to use the Union method but it creates a new List<> everytime. So I'd like to avoid doing something like this:
我希望能够使用 Union 方法,但它每次都会创建一个新的 List<> 。所以我想避免做这样的事情:
List<int> allInts = new List<int>();
foreach(List<int> list in listOfLists)
allInts = new List<int>(allInts.Union(list));
Any suggestions?
有什么建议?
Thanks!
谢谢!
采纳答案by flq
List<List<int>> l = new List<List<int>>();
l.Add(new List<int> { 1, 2, 3, 4, 5, 6});
l.Add(new List<int> { 4, 5, 6, 7, 8, 9 });
l.Add(new List<int> { 8, 9, 10, 11, 12, 13 });
var result = (from e in l
from e2 in e
select e2).Distinct();
Update 09.2013
2013 年 9 月更新
But these days I would actually write it as
但这些天我实际上会把它写成
var result2 = l.SelectMany(i => i).Distinct();
回答by Jon Skeet
How about:
怎么样:
HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
set.UnionWith(list);
}
return set.ToList();
回答by Amy B
List<int> result = listOfLists
.SelectMany(list => list)
.Distinct()
.ToList();