问题描述:在IEnumerable使用时显示警告

分析:如果对IEnumerable多次读取操作,会有因数据源改变导致前后两次枚举项不固定的风险,最突出例子是读取数据库的时候,第二次foreach时恰好数据源发生了改变,那么读取出来的数据和第一次就不一致了。

查看测试代码

几乎所有返回类型为 IEnumerable<T> 或 IOrderedEnumerable<TElement> 的标准查询运算符都以延迟方式执行。如下表我们可以看到where时,返回的IEnumerable是延迟加载的。

标准查询运算符

Return Type

立即执行

延迟流式执行

延迟非流式执行

Aggregate

TSource

   

All<TSource>

Boolean

   

Any

Boolean

   

AsEnumerable<TSource>

IEnumerable<T>

 

 

Average

单个数值

   

Cast<TResult>

IEnumerable<T>

 

 

Concat<TSource>

IEnumerable<T>

 

 

Contains

Boolean

   

Count

Int32

   

DefaultIfEmpty

IEnumerable<T>

 

 

Distinct

IEnumerable<T>

 

 

ElementAt<TSource>

TSource

   

ElementAtOrDefault<TSource>

TSource

   

Empty<TResult>

IEnumerable<T>

   

E√cept

IEnumerable<T>

 

First

TSource

   

FirstOrDefault

TSource

   

GroupBy

IEnumerable<T>

   

GroupJoin

IEnumerable<T>

 

Intersect

IEnumerable<T>

 

Join

IEnumerable<T>

 

Last

TSource

   

LastOrDefault

TSource

   

LongCount

Int64

   

Ma√

单个数值、TSource 或 TResult

   

Min

单个数值、TSource 或 TResult

   

OfType<TResult>

IEnumerable<T>

 

 

OrderBy

IOrderedEnumerable<TElement>

   

OrderByDescending

IOrderedEnumerable<TElement>

   

Range

IEnumerable<T>

 

 

Repeat<TResult>

IEnumerable<T>

 

 

Reverse<TSource>

IEnumerable<T>

   

Select

IEnumerable<T>

 

 

SelectMany

IEnumerable<T>

 

 

SequenceEqual

Boolean

   

Single

TSource

   

SingleOrDefault

TSource

   

Skip<TSource>

IEnumerable<T>

 

 

SkipWhile

IEnumerable<T>

 

 

Sum

单个数值

   

Take<TSource>

IEnumerable<T>

 

 

TakeWhile

IEnumerable<T>

 

 

ThenBy

IOrderedEnumerable<TElement>

   

ThenByDescending

IOrderedEnumerable<TElement>

   

ToArray<TSource>

TSource 数组

   

ToDictionary

Dictionary<TKey, TValue>

   

ToList<TSource>

IList<T>

   

ToLookup

ILookup<TKey, TElement>

   

Union

IEnumerable<T>

 

 

Where

IEnumerable<T>

 

 

 

解决方案:

多次使用IEnumerable时,最好转换为List或者Array

 

测试代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ConsoleApplication2.EF; namespace ConsoleApplication2
{
class Program_IEnumerable
{
static void Main(string[] args)
{
// 异步访问数据库
Task.Run(() =>
{
while (true)
{
reloadDb();
}
}); // 使用死循环不停的读取数据
int count = ;
while (true)
{
Console.WriteLine("第{0}读取", count);
IEnumerable<string> names = getNames(); var allNames = new StringBuilder();
foreach (var name in names)
allNames.Append(name + ",");
Thread.Sleep(); var allNames2 = new StringBuilder();
foreach (var name in names)
allNames2.Append(name + ",");
if (allNames2 != allNames)
Console.WriteLine("数据源发生了改变");
count++; Thread.Sleep();
} Console.ReadKey();
} static void reloadDb()
{
using (var infosEntities = new TestEntities())
{
infosEntities.Student.Add(new Student
{
EnrollmentDate = DateTime.Now,
FirstMidName = "han",
LastName = "zhu"
});
infosEntities.SaveChanges();
}
Thread.Sleep(); using (var infosEntities = new TestEntities())
{
var entity = infosEntities.Student.FirstOrDefault(a => a.FirstMidName == "han");
if (entity != null)
{
infosEntities.Student.Remove(entity);
infosEntities.SaveChanges();
}
}
Thread.Sleep();
} static IEnumerable<string> getNames()
{
var infosEntities = new TestEntities();
return infosEntities.Student.Select(a => a.FirstMidName + " " + a.LastName);
} } }

参考资料:

Resharper官方对于这个警告的描述:

https://www.jetbrains.com/help/resharper/PossibleMultipleEnumeration.html

MSDN的解释:

https://msdn.microsoft.com/zh-cn/library/vs/alm/bb882641(v=vs.90)/css

Resharper报“Possible multiple enumeration of IEnumerable”的更多相关文章

  1. Possible multiple enumeration of IEnumerable

    https://www.jetbrains.com/help/resharper/2016.1/PossibleMultipleEnumeration.html Consider the follow ...

  2. [报错]Fast enumeration variables cannot be modified in ARC by default; declare the variable __strong to allow this

    今天写了下面的快速枚举for循环代码,从按钮数组subButtons中取出button,然后修改button的样式,在添加到view中 for (UIButton *button in subButt ...

  3. web.xml里报错:Multiple annotations found at this line:

    在web.xml 中添加错误页面配置,出现了这个报错 具体情况是这样的: 错误信息: Multiple annotations found at this line: - cvc-complex-ty ...

  4. hibernate和mybatis出现配置文件xml的文件报错Multiple annotations found at this line(转)

    hibernate中的xml配置文件Multiple annotations found at this line,出现这个红叉报错,直接是把 <?xml version="1.0&q ...

  5. ASP.NET MVC报错: Multiple types were found that match the controller named

    当使用ASP.NET MVC的Area功能时,出现了这样的错误: Multiple types were found that match the controller named 'Home'. T ...

  6. 关于MyEclipse不停报错multiple problems have occurred 或者是内存不足 的解决办法

    这是因为 worksapace与svn代码不一样,要更新! 一更新就好了,困扰死我了,卧槽,搞了2个小时,难怪svn一提交就卡死人,原来还就是svn的问题,更新一下就行.

  7. 异常-----web.xml文件报错 Multiple annotations found at this line: - cvc-complex-type.2.4.b: The content of element 'welcome-file-list' is not complete. One of '{"http://java.sun.c

    1,检查抬头是不是有问题. <?xml version="1.0" encoding="UTF-8"?><web-app version=&q ...

  8. eclipse导入项目报错multiple annotations found at this line

    eclipsewindow-->preference-->Valdation-->将Manual和Build下复选框全部取消选择

  9. as报错 Multiple root tags Unexpected tokens 这个都是编译器识别问题

    从网上复制了个代码,直接复制上,结果一篇红线提示Unexpected tokens 通过去掉空格,还是无法根治,别的地方复制的就没有问题. 通过查看复制的网页源码 可以看到里边<> 这个符 ...

随机推荐

  1. Seven super tips for successful selling on Amazon

    Check for orders daily: To ship quickly you need to find out about orders promptly. We will e-mail y ...

  2. Python 招聘信息爬取及可视化

    自学python的大四狗发现校招招python的屈指可数,全是C++.Java.PHP,但看了下社招岗位还是有的.于是为了更加确定有多少可能找到工作,就用python写了个爬虫爬取招聘信息,数据处理, ...

  3. php中注释有关内容

    //单行注释 /*多行注释*/ /** 文档注释 (注意 文档注释与前面的那个多行注释不同)文档注释可以和特定的程序元素相关联 例如 类 函数 常量 变量方法 问了将文档注释与元素相关联 只需要在元素 ...

  4. RIGHT-BICEP测试第二次程序

    根据Right-BICEP单元测试的方法我对我写的第二次程序进行了测试: 测试一:测试能否控制使用乘除 测试二:测试是否能加括号 测试三:是否可以控制题目输出数量 测试四:能否控制输出方式,选择文件输 ...

  5. python 动态获取当前运行的类名和函数名的方法

    一.使用内置方法和修饰器方法获取类名.函数名 python中获取函数名的情况分为内部.外部,从外部的情况好获取,使用指向函数的对象,然后用__name__属性 复制代码代码如下: def a():pa ...

  6. HDU 5234 Happy birthday 01背包

    题目链接: hdu:http://acm.hdu.edu.cn/showproblem.php?pid=5234 bc:http://bestcoder.hdu.edu.cn/contests/con ...

  7. 周总结<3>

    经过了一周的学习,我们在html以及C语言方面又有的新的知识点的学习,包括计算机导论也学会了路由器的设置. html 鼠标事件 C 二叉树的遍历代码 计算机导论 路由器的设置 Html案例: < ...

  8. Java 数组转字符

    public static String toString(int[] arr){ String temp = ""; for(int i = 0;i<arr.length; ...

  9. Java中的网络编程-3

    用户数据协议(UDP)是网络信息传输的另外一种形式, 基于UDP的通信不同于基于TCP的通信, 基于UDP的信息传递更快, 但是不提供可靠的保证. 使用UDP传输数据时, 用户无法知道数据能否正确地到 ...

  10. scala程序运行的几种方式

    HelloWorld简单实例 object HelloWorld{ def main(args:Array[String]){ println("HelloWorld") } } ...