Env.: .NET4 C#
Hi All,
I want to combine these 2 lists : { \"A\", \"B\", \"C\", \"D\" }
and { \"1\", \"2\", \"3\" }
into this o
Use SelectMany when you want to form the Cartesian product of two lists:
aList.SelectMany(a => bList.Select(b => a + b))
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;
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 :)