问题描述:在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. scrapy+selenium+chromedriver解析动态渲染页面

    背景:动态页面是页面是通过js代码渲染出来的,无法直接使用scrapy爬虫,这是就需要先把js代码转为静态的html,再用scrapy爬虫就可以解决 解决办法:增加SeleniumMiddleware ...

  2. 用 Python 编写的 Python 解释器

    Allison是Dropbox的工程师,在那里她维护着世界上最大的由Python客户组成的网络.在Dropbox之前,她是Recurse Center的引导师, … 她在北美的PyCon做过关于Pyt ...

  3. Python坑系列:可变对象与不可变对象

    在之前的文章 http://www.cnblogs.com/bitpeng/p/4748148.html 中,大家看到了ret.append(path) 和ret.append(path[:])的巨大 ...

  4. 多源最短路——Floyd算法

    Floyd算法 问题的提出:已知一个有向网(或者无向网),对每一对定点vi!=vj,要求求出vi与vj之间的最短路径和最短路径的长度. 解决该问题有以下两种方法: (1)轮流以每一个定点为源点,重复执 ...

  5. Alpha 冲刺(7/10)

    队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 学习MSI.CUDA 试运行软件并调试 ...

  6. 严重: Failed to destroy end point associated with ProtocolHandler ["http-nio-8080"] java.lang.NullPointer

    刚接触servlet类,按照课本的方法使用eclipse新建了一个servlet类. 新建完成后,在web.xml里面进行注册 这时候就会报错了. 五月 07, 2016 11:23:28 上午 or ...

  7. lintcode-383-装最多水的容器

    383-装最多水的容器 给定 n 个非负整数 a1, a2, ..., an, 每个数代表了坐标中的一个点 (i, ai).画 n 条垂直线,使得 i 垂直线的两个端点分别为(i, ai)和(i, 0 ...

  8. 【第四周】psp

    代码累计 300+575+475+353=1603 随笔字数 1700+3000+3785+4210=12695 知识点 QT框架 Myeclipse基础环境 代码复用,封装 Ps技术 在excel画 ...

  9. CodeForces Round #527 (Div3) B. Teams Forming

    http://codeforces.com/contest/1092/problem/B There are nn students in a university. The number of st ...

  10. c 用指针操作结构体数组

    重点:指针自加,指向下一个结构体数组单元 #include <stdio.h> #include <stdlib.h> #include <string.h> #d ...