views:

1240

answers:

3

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!

+8  A: 

How about:

HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
    set.UnionWith(list);
}
return set.ToList();
Jon Skeet
This is nice. I didn't know that the HashSet had a UnionWith method. Thanks.
perfect job for a reduce function if it existed in linq.
Spence
I personally like this approach... use a set since it will eliminate duplicates. No magic here. It works anywhere ;)
D.Shawley
+16  A: 
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();
flq
This is in many ways a nicer solution than mine. +1.
Jon Skeet
This is what I was looking for. Just add a .ToList() at the end of the Distinct and I have what I need. Thanks!
My comment was aka "Darn - why didn't I think of that?" :)
Jon Skeet
It might be faster then Jon's solution , but I think Jon's is more readable.
Frederik Gheysels
+1 for beautiful code
ctacke
+1 for having Jon tell you it was a nicer solution. ;)
j0rd4n
+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
+5  A: 
List<int> result = listOfLists
  .SelectMany(list => list)
  .Distinct()
  .ToList();
David B