Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine 2 lists using LINQ?

Env.: .NET4 C#

Hi All,

I want to combine these 2 lists : { "A", "B", "C", "D" } and { "1", "2", "3" }

into this one:

{ "A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3", "D1", "D2", "D3" }

Obviously, i could use nested loops. But I wonder if LINQ can help. As far as I understand, Zip() is not my friend in this case, right?

TIA,

like image 677
Serge Wautier Avatar asked Jan 26 '11 08:01

Serge Wautier


People also ask

What is Union C#?

CsharpProgrammingServer Side Programming. The Union method gets the unique elements from both the lists. Let us set two lists − var list1 = new List<int>{12, 65, 88, 45}; var list2 = new List<int>{40, 34, 65}; Now get the union of both the lists − var res = list1.Union(list2);


3 Answers

Essentially, you want to generate a cartesian product and then concatenate the elements of each 2-tuple. This is easiest to do in query-syntax:

var cartesianConcat = from a in seq1
                      from b in seq2
                      select a + b;
like image 41
Ani Avatar answered Oct 07 '22 04:10

Ani


Use SelectMany when you want to form the Cartesian product of two lists:

aList.SelectMany(a => bList.Select(b => a + b))

like image 193
Ian Mercer Avatar answered Oct 07 '22 04:10

Ian Mercer


SelectMany is definitely the right approach, whether using multiple "from" clauses or with a direct call, but here's an alternative to Hightechrider's use of it:

var result = aList.SelectMany(a => bList, (a, b) => a + b);

I personally find this easier to understand as it's closer to the "multiple from" version: for each "a" in "aList", we produce a new sequence - in this case it's always "bList". For each (a, b) pair produced by the Cartesian join, we project to a result which is just the concatenation of the two.

Just to be clear: both approaches will work. I just prefer this one :)

As to whether this is clearer than the query expression syntax... I'm not sure. I usually use method calls when it's just a case of using a single operator, but for Join, GroupJoin, SelectMany and GroupBy, query expressions do simplify things. Try both and see which you find more readable :)

like image 23
Jon Skeet Avatar answered Oct 07 '22 03:10

Jon Skeet