收益回报与回报选择
两种方法的优点/缺点是什么?
return items.Select(item => DoSomething(item));
与
foreach(var item in items)
{
yield return DoSomething(item);
}
EDIT 由于它们大致相当于 MSIL,您认为哪一个更具可读性?
Which are the advantages/drawbacks of both approaches?
return items.Select(item => DoSomething(item));
versus
foreach(var item in items)
{
yield return DoSomething(item);
}
EDIT As they are MSIL roughly equivalent, which one you find more readable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
yield return
技术使 C# 编译器“在幕后”生成枚举器类,而Select
调用则使用通过委托参数化的标准枚举器类。实际上,除了在Select
情况下委托的可能有一个额外的调用帧之外,两者之间不应该有太大的区别。就其价值而言,将 lambda 包裹在 DoSomething 周围也是毫无意义的;只需直接为其传递一个委托即可。
The
yield return
technique causes the C# compiler to generate an enumerator class "behind the scenes", while theSelect
call uses a standard enumerator class parameterized with a delegate. In practice, there shouldn't be a whole lot of difference between the two, other than possibly an extra call frame in theSelect
case, for the delegate.For what it's worth, wrapping a lambda around
DoSomething
is sort of pointless as well; just pass a delegate for it directly.在缓慢发展的企业世界中,我目前花费的时间比我希望的要多,收益回报具有巨大的优势,它不需要至少在 2 年内不会安装的全新 .NET 3.5 框架。
In the slow-moving corporate world where I currently spend more time than I'd wish, yield return has the enormous advantage that it doesn't need that brand new .NET 3.5 Framework that won't be installed for at least another 2 years.
选择仅允许您为“items”集合中的每一项返回一个对象。
使用额外的
.Where(x => DoIReallyWantThis(x))
可以让您清除不需要的项目,但仍然只允许您为每个项目返回一个对象。如果您希望每一项可能有多个对象,则可以使用
.SelectMany
但很容易会导致一行很长且不易阅读的情况。如果您正在查看复杂的数据结构并到处挑选一些信息,那么“yield return”有可能使您的代码更具可读性。我见过的最好的例子是,大约有十几个单独的条件会导致返回对象,并且在每种情况下,返回的对象的构造方式都不同。
Select only allows you to return one object for each item in your "items" collection.
Using an additional
.Where(x => DoIReallyWantThis(x))
allows you to weed out unwanted items, but still only allows you to return one object per item.If you want potentially more than one object per item, you can use
.SelectMany
but it is easy to wind up with a single long line that is less than easy to read."yield return" has the potential to make your code more readable if you are looking through a complex data structure and picking out bits of information here and there. The best example of this that I have seen was where there were around a dozen separate conditions which would result in a returned object, and in each case the returned object was constructed differently.