.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#,
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).
// 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”.
–EOF (The Ultimate Computing & Technology Blog) —
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
