문제

나는있다 List<List<int>>. 나는 그것을 a로 변환하고 싶습니다 List<int> 각 int가 독특한 곳. LINQ를 사용하여 누군가가 이것에 대한 우아한 해결책을 가지고 있는지 궁금했습니다.

Union 메소드를 사용할 수 있지만 매번 새로운 목록 <>을 만듭니다. 그래서 나는 다음과 같은 일을 피하고 싶습니다.

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

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

제안이 있습니까?

감사!

도움이 되었습니까?

해결책

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();

업데이트 09.2013

그러나 요즘 나는 실제로 그것을 쓸 것입니다

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

다른 팁

List<int> result = listOfLists
  .SelectMany(list => list)
  .Distinct()
  .ToList();

어때요 :

HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
    set.UnionWith(list);
}
return set.ToList();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top