Union List Lists Using Linq

It is not that difficult, but I cannot wrap it in linq.

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

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

Basically I want to return every unique row from ListOfLists; this is easy to use with a foreach loop and a storage variable (I could probably increase the effectiveness of not having a clear one at the very end, but it’s not):

 List<string> result = new List<string>(); foreach (var v in ListOfLists) { foreach (var s in v) { result.Add(s); } } result.Distinct(); 

How to do it with linq?

+6
source share
4 answers
 var distinctStrings = ListOfLists.SelectMany(list => list).Distinct(); 
+8
source

For completeness, the syntax of the query expression is sometimes easier to find (I find) than the correct call to SelectMany . Here it will be:

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

EDIT: to improve performance, use:

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

or

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

Source: https://habr.com/ru/post/896758/


All Articles