C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ)

C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ)

  • Comments 8

From code name “cool” to C# 3.0, it’s been a long journey for this amazing language with .NET Runtime. Here I am going to show you the evaluation step by step.

 

Let us assume we have generic list of integers and I need to find the even numbers from that list,

 

List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 

C# Way: Beginners

+++++++++++++

List<int> even1 = new List<int>();

 

foreach (int i in arrInt)

{

    if (i % 2 == 0)

        even1.Add(i);               

}

 

foreach (int item in even1)

{

    Console.WriteLine(item);

}

 

 

C# 1.1 Way: Using Delegate

+++++++++++++++++++

Using Predicate<T> we can call delegate and then with some existing method’s help I can get the data as I require.

 

So the method I need here will look like,

 

public static bool EvenGetter(int i2)

{

    return i2 % 2 == 0;

}

 

Now the predicate implementation seems something like,

 

List<int> even1 = arrInt.FindAll(new Predicate<int>(EvenGetter));

 

foreach (int item in even1)

{

    Console.WriteLine(item);

}

 

C# 2.0 Way: Using Anonymous Method

++++++++++++++++++++++++++

 

Anonymous Methods helps us to implement delegate without having any method.

 

List<int> even1 = arrInt.FindAll(delegate(int i2) { return i2 % 2 ==0; });

 

foreach (int item in even1)

{

    Console.WriteLine(item);

}

 

C# 3.0 Way: Using Lambda Expression

++++++++++++++++++++++++++

Hmm, this is magic. Please refer C# 3.0 Specification for more information.

 

List<int> even1 = arrInt.FindAll(i => i % 2 == 0);

 

foreach (int item in even1)

{

    Console.WriteLine(item);

}

 

C# 3.0 Way: Implementing LINQ

++++++++++++++++++++++

Write SQL like query as native statement, LINQ Rocks!!!

 

IEnumerable<int> even1 = from i in arrInt

                         where i % 2 == 0

                         select i;

 

foreach (int item in even1)

{

    Console.WriteLine(item);

}

 

This is the actual conversion happens when you compile the above code.

IEnumerable<int> even1 = arrInt.Where(i => i % 2 == 0);

 

Actual IL (disassembled) generated code looks like,

IEnumerable<int> even1 = <>g__initLocal0.Where<int>(delegate (int i) {

        return (i % 2) == 0;

    });

 

Pure code.

 

Namoskar!!!

Leave a Comment
  • Please add 3 and 6 and type the answer here:
  • Post
Page 1 of 1 (8 items)