C# LINQ: Possible Multiple Enumeration of IEnumerable (Resharper)


.NET offers the LINQ to write code in a concise and elegant way. In most of cases, there is no performance difference between a LINQ statement and its normal (foreach) statement. However, LINQ statement does not get executed immediately but the statement query is stored.

Considering the following piece of code in C#,

1
2
3
4
5
var test = Enumerable.Range(1, 100);
var a = test.Where(n => n%2 == 0);
var b = a.Sum();
var c = a.Count();
var d = from x in a where x%2 == 0 select x;
var test = Enumerable.Range(1, 100);
var a = test.Where(n => n%2 == 0);
var b = a.Sum();
var c = a.Count();
var d = from x in a where x%2 == 0 select x;

The test is a Enumerable from 1 to 100. The a variable returns the even numbers between 1 to 100 (however, it is just a query and it does not run immediately). The variables b, c, and d will run multiple queries (3 times). If the number of dataset is large that certainly there will be a performance bottleneck. To easy way to fix this is to cache the query result by simply adding a ToList() or ToArray() after LINQ so that the query result is saved (cached).

1
2
3
4
5
6
// helloacm.com
var test = Enumerable.Range(1, 100);
var a = test.Where(n => n%2 == 0).ToList(); // or ToArray()
var b = a.Sum();
var c = a.Count();
var d = from x in a where x%2 == 0 select x;
// helloacm.com
var test = Enumerable.Range(1, 100);
var a = test.Where(n => n%2 == 0).ToList(); // or ToArray()
var b = a.Sum();
var c = a.Count();
var d = from x in a where x%2 == 0 select x;

The good news is that the Resharper plugin will automatically warn this by hint: “Possible Multiple Enumeration of IEnumerable”.

linq-possible-multiple-enumeration-of-ienumerable C# LINQ: Possible Multiple Enumeration of IEnumerable (Resharper) c # optimization programming languages

linq-possible-multiple-enumeration-of-ienumerable

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
335 words
Last Post: How to Capture Command Output from VBScript at Window Scripting Host?
Next Post: How to Create and Run Unit Tests in C# .NET - A Quick Tutorial

The Permanent URL is: C# LINQ: Possible Multiple Enumeration of IEnumerable (Resharper)

7 Comments

  1. Naibedya Kar
  2. Anon
  3. Harry Vu

Leave a Reply