问题描述:在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. 0917 词法分析程序(java版)

    1.运行结果: 2.源代码: package 词法分析;import java.util.Scanner;public class fenxi {public static void main(Str ...

  2. OGNL动态实现result

    OGNL就是struts.xml文件中的<result>通过get()方法,动态获取action类中的变量 <struts> <package name="de ...

  3. 按照Right-BICEP要求设计的测试用例

    测试用例: 测试方法:Right-BICEP 测试要求: Right-结果是否正确? B-是否所有的边界条件都是正确的? P-是否满足性能要求? 题目是否有重复? 数量是否可定制? 数值范围是否可定制 ...

  4. TensorFlow:NameError: name ‘input_data’ is not defined

    在运行TensorFlow的MNIST实例时,第一步 import tensorflow.examples.tutorials.mnist.input_data mnist = input_data. ...

  5. c艹第三次作业

    1.git地址,不要介意仓库名. https://github.com/b666666666666666b/elevator-schedualing 2.首先,我先说一下我是怎么实现三个电梯的. 首先 ...

  6. Task Class .net4.0异步编程类

    文章:Task Class 地址:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.task?view=netfra ...

  7. OC创建对象并访问成员变量

    1.创建一个对象 Car *car =[Car new] 只要用new操作符定义的实体,就会在堆内存中开辟一个新空间 [Car new]在内存中 干了三件事 1)在堆中开辟一段存储空间 2)初始化成员 ...

  8. APUE(unix环境高级编程)第三版---first day---部署书中实例的运行环境(apue.h)

    操作环境:RHEL7.0 部署apue.h实例运行环境 1.下载头文件src.3e.tar.gz 2.解压 tar zxvf src.3e.tar.gz 3.创建普通用户(我仿照书上创建的sar用户) ...

  9. equals()和hashcode()详解

    转载自http://www.cnblogs.com/Qian123/p/5703507.html java.lang.Object类中有两个非常重要的方法:   public boolean equa ...

  10. Mysql的表名/字段名/字段值是否区分大小写

    1.MySQL默认情况下是否区分大小写,使用show Variables like '%table_names'查看lower_case_table_names的值,0代表区分,1代表不区分. 2.m ...