.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”.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
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
Pretty nicely explained. Cheers!!
This was a nice simple example that cleanly explained what is happening behind the scenes and why this message is popping up. Thanks for the short post on it.
Thanks, glad it helps.
Simply the best explanation on this topic. Thanks.
Glad you like it.
This is the best example I’ve read explaining multiple Enumeration. After reading this, you have me asking myself, what took me so long to fully understand something so simple.
Thanks,
Glad it helps 🙂