How to combine 2 lists using LINQ?

后端 未结 3 1406
一向
一向 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:29

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

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

    0 讨论(0)
  • 2021-02-02 09:32

    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;
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题