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.
Not Exactly a Union, but you can try this
YourList.SelectMany(l=>l).Distinct()
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()'
You can use the SelectMany extension method.
List<List<String>> masterList = { {"A" , "B" }, {"C" , "D" } };
IEnumerable<string> results = masterList.SelectMany(l => l);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With