Can these two LINQ queries be used interchangeably?

后端 未结 2 551
南旧
南旧 2021-01-19 15:56

a) Would the following two queries produce the same results:

  var query1 = collection_1
            .SelectMany(c_1 => c_1.collection_2)
            .Se         


        
2条回答
  •  灰色年华
    2021-01-19 16:01

    The snippets you've given seem to be invalid. c_3 isn't defined in the scope of the Select statement, so unless I've misunderstood something, this won't compile.

    It seems as though you're trying to select the elements of collection_3, but this is done implicitly by SelectMany, and so the final Select statements in both cases are redundant. Take them out, and the two queries are equivalent.

    All you need is this:

    var query = collection_1
               .SelectMany(c_1 => c_1.collection_2)
               .SelectMany(c_2 => c_2.collection_3);
    

    Update: x => x is the identity mapping, so Select(x => x) is always redundant, regardless of the context. It just means "for every element in the sequence, select the element".

    The second snippet is of course different, and the SelectMany and Select statements indeed need to be nested in order to select all three elements, c_1, c_2, and c_3.

    Like Gert, says, though, you're probably better off using query comprehension syntax. It's much more succinct and makes it easier to mentally parse the workings of a query.

提交回复
热议问题