Tuesday, April 5, 2011

Convert List<List<T>> into List<T> in C#

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!

From stackoverflow
  • How about:

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

0 comments:

Post a Comment