How to combine 2 lists using LINQ?

后端 未结 3 1407
一向
一向 2021-02-02 09:15

Env.: .NET4 C#

Hi All,

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

into this o

3条回答
  •  既然无缘
    2021-02-02 09:50

    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 :)

提交回复
热议问题