23

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!

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
user57230
  • 233
  • 1
  • 2
  • 5

3 Answers3

66
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();
flq
  • 22,247
  • 8
  • 55
  • 77
  • This is what I was looking for. Just add a .ToList() at the end of the Distinct and I have what I need. Thanks! – user57230 Jan 20 '09 at 20:19
  • +1 because this rocks -- have you considered putting in a "where e != null" though, so it does not start throwing things when you have a null list inside your list? – Ria Jan 21 '09 at 06:13
17
List<int> result = listOfLists
  .SelectMany(list => list)
  .Distinct()
  .ToList();
Amy B
  • 108,202
  • 21
  • 135
  • 185
10

How about:

HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
    set.UnionWith(list);
}
return set.ToList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194