Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union A List of Lists Using Linq

Tags:

c#

linq

This isn't that complicated of a question, but I can't wrap my head around it in linq.

I have an Enumerable<T> containing an Enumerable<string>:

public class
{
   List<List<string>> ListOfLists = new List<List<string>>();
}

I basically want to return each unique string from ListOfLists; this is easy using a foreach loop and a storage variable (I could probably improve the efficiency of not having the distinct at the very end, but that's not the point):

List<string> result = new List<string>();

foreach (var v in ListOfLists)
{
   foreach (var s in v)
   {
      result.Add(s);
   }
}

result.Distinct();

How do I do this with linq?

like image 309
Daniel Avatar asked Sep 07 '11 02:09

Daniel


2 Answers

var distinctStrings = ListOfLists.SelectMany(list => list).Distinct();
like image 159
cordialgerm Avatar answered Oct 14 '22 19:10

cordialgerm


Use SelectMany. See http://msdn.microsoft.com/en-us/library/bb534336.aspx

like image 43
Ian Mercer Avatar answered Oct 14 '22 19:10

Ian Mercer