可以将这两个LINQ查询可以互换使用? [英] Can these two LINQ queries be used interchangeably?

查看:125
本文介绍了可以将这两个LINQ查询可以互换使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a)项下面两个查询产生相同的结果:

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

  var query1 = collection_1
            .SelectMany(c_1 => c_1.collection_2)
            .SelectMany(c_2 => c_2.collection_3)
            .Select(c_3 => c_3);

  var query2 = collection_1
            .SelectMany(c_1 => c_1.collection_2
            .SelectMany(c_2 => c_2.collection_3.Select(c_3 => c_3)));



二)我假定这两个查询不能总是交替使用?例如,如果我们想要输出的元素也包含值 C_1 C_2 ,那么我们只有做到这一点 QUERY2 ,但不能与 QUERY1

b) I assume the two queries can't always be used interchangeably? For example, if we wanted the output elements to also contain values of c_1 and c_2, then we only achieve this with query2, but not with query1:

  var query2 = collection_1
            .SelectMany(c_1 => c_1.collection_2
            .SelectMany(c_2 => c_2.collection_3.Select(c_3 => new { c_1, c_2, c_3 } )));



?

感谢您

推荐答案

您已经给该片段似乎是无效的。 C_3 未在选择语句的范围界定,所以,除非我误解的东西,这亿韩元 ŧ编译。

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.

这好像你要选择的 collection_3 的元素,但这样做隐含的SelectMany ,因此,在这两种情况下最终选择语句是多余的。 。带他们出去,两个查询是等效的。

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






更新: X => X 是标识映射,那么选择(X => X)永远是多余的,不管上下文。它只是意味着为序列中的每一个元素,选择该元素。


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".

第二个片段,当然是不同的,而的SelectMany 选择语句确实需要嵌套,以选择所有三个元素, C_1 C_2 C_3

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.

这篇关于可以将这两个LINQ查询可以互换使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆