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,
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);
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;
Use SelectMany when you want to form the Cartesian product of two lists:
aList.SelectMany(a => bList.Select(b => a + b))
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 :)
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