LINQ的可能用途选择(X => X) [英] Possible purpose of LINQ select( x => x )

查看:144
本文介绍了LINQ的可能用途选择(X => X)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一本书上的MVC经历了一些LINQ的例子,我想知道下面的选择调用能有什么目的。也许这是一个错字,但我没有看到这本书的勘误表的任何提及。

I'm going through some LINQ examples from a book on MVC and I'm wondering what purpose the select call below could have. Maybe it's a typo but I don't see any mention of it in the book's errata.

foreach( Product p in products
    .Where( e => e.Name == productParam.Name )
    .Select( e => e ) ) {
        p.Price = productParam.Price;
}



我测试了这个地方。选择(E =>电子两个例子)被列入并且之一,它是不和代码是相同的。因为如果返回了IEnumerable由谓词过滤,然后将时选择调用(与特定谓语以上)永远是必要的吗?它实际上做什么吗?莫非在一些奇怪的角落呢?

I tested out two examples of this where the .Select( e => e) was included and one where it was not and the code is the same. Since Where returns the IEnumerable filtered by the predicate then when would the select call (with the specific predicate above) ever be necessary? Does it actually do anything? Could it in some weird corner case?

推荐答案

这将返回完全相同的东西,没有它,一个的 的IEnumerable< T> 。它atually做弊大于利,虽然,因为它的执行冗余O(n)操作(整个列表循环)。

It would return the exact same thing as without it, an IEnumerable<T>. It's atually doing more harm than good though as it's performing a redundant O(n) operation (looping through the whole list).

参考

  • MSDN - Enumerable.Select
  • MSDN - Enumerable.Where

这篇关于LINQ的可能用途选择(X =&GT; X)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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