简体   繁体   中英

Union A List of Lists Using 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?

var distinctStrings = ListOfLists.SelectMany(list => list).Distinct();

For completeness, the query expression syntax is sometimes easier (I find) to come up with than the correct invocation of SelectMany . Here it would be:

result = (from list in ListOfLists
          from s in list
          select s).Distinct().ToList();
var result = ListOfLists.SelectMany(v => v).ToList().Distinct();

EDIT: For better performance, use:

var result = ListOfLists.SelectMany(v => v).Distinct();

or

var result = ListOfLists.SelectMany(v => v).Distinct().ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM