ReSharper的:IEnumerable的的可能的多个枚举 [英] Resharper: Possible Multiple Enumeration of IEnumerable

查看:219
本文介绍了ReSharper的:IEnumerable的的可能的多个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是新版本的ReSharper的6.在我的代码好几个地方已经强调了一些文本,并警告我,有可能是IEnumerable的的的可能多枚举

I'm using the new Resharper version 6. In several places in my code it has underlined some text and warned me that there may be a Possible multiple enumeration of IEnumerable.

我明白这意味着什么,并采取建议在适当情况下,但在某些情况下,我不知道它实际上是一个大问题。

I understand what this means, and have taken the advice where appropriate, but in some cases I'm not sure it's actually a big deal.

就像下面的代码:

var properties = Context.ObjectStateManager.GetObjectStateEntry(this).GetModifiedProperties();
if (properties.Contains("Property1") || properties.Contains("Property2") || properties.Contains("Property3")) {
    ...
}

它强调属性的每一个提到的第二行警告说,我列举了这IEnumerable的多次。

It's underlining each mention of properties on the second line, warning that I am enumerating over this IEnumerable multiple times.

如果我想补充 .ToList()来结束1号线(转动属性的IEnumerable<串> 列表<串> )的警告消失。

If I add .ToList() to the end of line 1 (turning properties from a IEnumerable<string> to a List<string>), the warnings go away.

但可以肯定,如果我把它转换成一个列表,然后它会枚举在整个IEnumerable的建立列表中的第一个地方,然后枚举名单按要求找到的属性(即1个整体枚举和3部分枚举)。而在我的原代码,它只是在做局部3枚举。

But surely, if I convert it to a List, then it will enumerate over the entire IEnumerable to build the List in the first place, and then enumerate over the List as required to find the properties (i.e. 1 full enumeration, and 3 partial enumerations). Whereas in my original code, it is only doing the 3 partial enumerations.

难道我错了吗?什么是这里最好的方法是什么?

Am I wrong? What is the best method here?

推荐答案

我不知道究竟你的属性真的是在这里 - 但如果它本质上代表一个unmaterialized数据库查询,那么你的如果语句将执行三个查询

I don't know exactly what your properties really is here - but if it's essentially representing an unmaterialized database query, then your if statement will perform three queries.

我的犯罪嫌疑人的这将是更好的事:

I suspect it would be better to do:

string[] propertiesToFind = { "Property1", "Property2", "Property3" };
if (properties.Any(x => propertiesToFind.Contains(x))
{
     ...
}

这会的逻辑的只能通过序列重复一次 - 如果有涉及到数据库查询,这很可能是能够只使用一个SQLIN的条款做这一切在一个查询数据库。

That will logically only iterate over the sequence once - and if there's a database query involved, it may well be able to just use a SQL "IN" clause to do it all in the database in a single query.

这篇关于ReSharper的:IEnumerable的的可能的多个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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