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…

Combinable enums in .net

As well as creating normal enums we can create combined enum values. To do this decorate the enum with a Flags attribute this allows the string to output the combination of names.We also need to provide specific values for each member and we do this power of two for example 0,1,2,4,8.

Example

[Flags]
public enum Sides
{
None=0,
Left=1,
Right=2,
Top=4,
Bottom=8
}
public class EnumCombinationsDemo
{
public static void Test()
{
var leftRightCombination = Sides.Left | Sides.Right;//Output : Left | Right
var topBottomCombination = Sides.Top | Sides.Bottom;//Output : Top | Bottom
bool isTopIncluded = topBottomCombination.HasFlag(Sides.Top); //Output : true
//Combining combinations
var allCombinations = leftRightCombination | topBottomCombination; //Output : Left | Right | Top | Bottom
//toggling values
allCombinations ^= Sides.Top; //Output : Left | Right | Bottom
allCombinations ^= Sides.Top; //Output : Left | Right | Top | Bottom
}
}

Enjoy coding…