Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Union List<List<String>> in C#

Tags:

c#

lambda

linq

I'm having a List<List<String>>, and which contains

{  {"A" , "B" }, 
   {"C" , "D" }
}

I need to union all the innerlist into another list

So the resulting List<String> will contain

     {"A","B","C","D"}

Now im using for loop to do this

Is there any way to do this Using LINQ or Lambda Expression.

Please help me to do this.

Thanks in advance.

like image 586
Thorin Oakenshield Avatar asked Dec 23 '10 04:12

Thorin Oakenshield


3 Answers

Not Exactly a Union, but you can try this

YourList.SelectMany(l=>l).Distinct()
like image 151
Alexander Taran Avatar answered Oct 16 '22 11:10

Alexander Taran


List<List<string>> collections = new List<List<string>>()
        {
          new List<string>(){"A" , "B" }, 
          new List<string>() {"C" , "D" }
        };

var list = collections.SelectMany(x => x).ToList();

SelectMany builds up a expression tree that when evaluated flattens the list of list to a single list of combined members.

ToList forces the expression tree to be evaluated and which results in a List.

If you want to eliminate duplicates you can add a Distinct call before the call to 'ToList()'

like image 24
JR Kincaid Avatar answered Oct 16 '22 13:10

JR Kincaid


You can use the SelectMany extension method.

List<List<String>> masterList = { {"A" , "B" }, {"C" , "D" } };

IEnumerable<string> results = masterList.SelectMany(l => l);
like image 20
sgriffinusa Avatar answered Oct 16 '22 12:10

sgriffinusa