转换列表<名单,LT; T>>进入名单< T>在C#中 [英] Convert List<List<T>> into List<T> in C#

查看:121
本文介绍了转换列表<名单,LT; T>>进入名单< T>在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表与LT;名单< INT>> 。我想它转换成列表与LT; INT> 中的每个int是独一无二的。我想知道如果任何人有一个优雅的解决方案,这一点使用LINQ



我想是能够使用联盟的方法,但它会创建一个新的List<>每次。所以我想,以避免做这样的事情:

 列表< INT> allInts =新的List< INT>(); 

的foreach(列表< INT>列表listOfLists)
allInts =新的List< INT>(allInts.Union(列表));

有什么建议?



谢谢!


解决方案

 列表<名单,LT; INT>> L =新的List<名单,LT; INT>>(); 

l.Add(新列表与所述; INT> {1,2,3,4,5,6});
l.Add(新列表与所述; INT> {4,5,6,7,8,9});
l.Add(新列表与所述; INT> {8,9,10,11,12,13});

VAR的结果=(从电子交运集团
从E2在电子
选择E2).Distinct();



更新09.2013



但这些天我实际上它写成

  VAR RESULT2 = l.SelectMany(I = I标记).Distinct(); 


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.

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:

List<int> allInts = new List<int>();

foreach(List<int> list in listOfLists)
   allInts = new List<int>(allInts.Union(list));

Any suggestions?

Thanks!

解决方案

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

But these days I would actually write it as

var result2 = l.SelectMany(i => i).Distinct();

这篇关于转换列表&LT;名单,LT; T&GT;&GT;进入名单&LT; T&GT;在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆