Avoid Multiple enumeration of IEnumerable

When we working with Linq queries it’s important to know that  query doesn’t get executed when we define it. Rather it’s get executed we actually use it or enumerated it.

Possible Multiple Enumeration

//Avoid Reevaluating of Linq Queries
Console.WriteLine("First Enumeration");
var nums = new List<int> {1,2,3,4};
var result = from n in nums select new {Number=n,ExecutionTime=DateTime.Now.ToString("mm:ss:fff")};
foreach (var item in result)
{
Console.WriteLine(item);
}
foreach (var item in result)
{
Console.WriteLine(item);
}

Console.WriteLine(“Second Enumeration”);

Avoid Multiple enumeration Of IEnumerable

Console.WriteLine(“Second Enumeration”);
//You can avoid the multiple enumeration possible by converting the results to List,Dictionary,Array..
var goodresult = (from n in nums select new { Number = n, ExecutionTime = DateTime.Now.ToString("mm:ss:fff") }).ToList();
foreach (var item in goodresult)
{
Console.WriteLine(item);
}
foreach (var item in goodresult)
{
Console.WriteLine(item);
}

Enjoy..Coding…

One thought on “Avoid Multiple enumeration of IEnumerable

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s