# Posts Tagged ‘lambda’

## One Line Lambda–Lookup list of Lambda Expressions for common scenarios

Posted by Jean Paul on December 7, 2010

I have observed that Lambda Expressions got good steam among developers.  It helps us in reducing lot of code and save time.

I would like to list some of the useful Lambda Expressions here comparing with the without-lambda approach.

Common Setup Code

Here the common initialization code for using the below examples are given:

List<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

 Scenario Lambda Approach Traditional Approach Descending Sort list.OrderByDescending(i => i); list.Sort(delegate(int x, int y)     {         return y.CompareTo(x);     }); Check all numbers are less than 100 bool result = list.All(i => i < 100); bool result = true; foreach (int i in list)     if (i >= 100)         result = false; Check any numbers are equal to 5 bool result = list.Any(i => i == 5); bool result = false; foreach (int i in list)     if (i == 5)         result = true; Get the top 5 items in the list var sublist = list.Take(3); var sublist = new List(); for (int i = 0; i < 5; i++)     if (i < list.Count)         sublist.Add(i); Sort descending, get all numbers less than 8, take the top 5 var result = list.OrderByDescending(i => i).Where(i => i < 8).Take(5); list.Sort(delegate(int x, int y) {      return y.CompareTo(x);  });   List result = new List(); foreach (int i in list)     if (i < 8 )         if (result.Count < 5)             result.Add(i);

Summary

I think the examples above demonstrate, how complex the code will look even if you do the simple sorting and selection.

Surely Lambda Expressions is worth learning and in the long run it would give more manageable code.

Note

In the sorting scenario above, the original list is not updated, OrderBy() will be giving a sorted view of the original list.

For assigning it back to the original list we have to use the ToList<int>() method as:

list = list.OrderByDescending(i => i).ToList<int>();

## One Line Lambda–Lookup list of Lambda Expressions for common scenarios

Posted by Jean Paul on December 7, 2010

I have observed that Lambda Expressions got good steam among developers.  It helps us in reducing lot of code and save time.

I would like to list some of the useful Lambda Expressions here comparing with the without-lambda approach.

Common Setup Code

Here the common initialization code for using the below examples are given:

List<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

 Scenario Lambda Approach Traditional Approach Descending Sort list.OrderByDescending(i => i); list.Sort(delegate(int x, int y)     {         return y.CompareTo(x);     }); Check all numbers are less than 100 bool result = list.All(i => i < 100); bool result = true; foreach (int i in list)     if (i >= 100)         result = false; Check any numbers are equal to 5 bool result = list.Any(i => i == 5); bool result = false; foreach (int i in list)     if (i == 5)         result = true; Get the top 5 items in the list var sublist = list.Take(3); var sublist = new List(); for (int i = 0; i < 5; i++)     if (i < list.Count)         sublist.Add(i); Sort descending, get all numbers less than 8, take the top 5 var result = list.OrderByDescending(i => i).Where(i => i < 8).Take(5); list.Sort(delegate(int x, int y) {      return y.CompareTo(x);  });   List result = new List(); foreach (int i in list)     if (i < 8 )         if (result.Count < 5)             result.Add(i);

Summary

I think the examples above demonstrate, how complex the code will look even if you do the simple sorting and selection.

Surely Lambda Expressions is worth learning and in the long run it would give more manageable code.

Note

In the sorting scenario above, the original list is not updated, OrderBy() will be giving a sorted view of the original list.

For assigning it back to the original list we have to use the ToList<int>() method as:

list = list.OrderByDescending(i => i).ToList<int>();

## One Line Lambda – To select last 3 items in the list and find sum

Posted by Jean Paul on December 5, 2010

Here I am trying to show the advantage of Lambda Expression in code reduction and time saving.

Scenario

You have got a list containing 10 items.

1

2

3

4

5

6

7

8

9

10

You need to get the sum of last 3 items in the list.

Normal Approach

In a normal approach, we have to start from the last item in a for loop and decrementing the index variable.

IList<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int sum = 0;
for (int i = list.Count – 1; i >= list.Count – 3; i–)
sum += list[i];

Lambda Approach

The same functionality can be applied in a single line using the inbuilt methods Reverse(), Take() and Sum().

// Single line of code to attain the above task

## int sum = list.Reverse().Take(3).Sum();

Code Explained

The method Reverse() reverses the list

The method Take() takes the specified number of items

The method Sum() performs the sum operation

Summary

In the above scenario, Lamba helped us from

1. Little hectic code of for loop and decrementing index
2. Reduced the number of lines from 3 to 1
3. Helped in attaining the functionality in ease

## One Line Lambda – To select last 3 items in the list and find sum

Posted by Jean Paul on December 5, 2010

Here I am trying to show the advantage of Lambda Expression in code reduction and time saving.

Scenario

You have got a list containing 10 items.

1

2

3

4

5

6

7

8

9

10

You need to get the sum of last 3 items in the list.

Normal Approach

In a normal approach, we have to start from the last item in a for loop and decrementing the index variable.

IList<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int sum = 0;
for (int i = list.Count – 1; i >= list.Count – 3; i–)
sum += list[i];

Lambda Approach

The same functionality can be applied in a single line using the inbuilt methods Reverse(), Take() and Sum().

// Single line of code to attain the above task

## int sum = list.Reverse().Take(3).Sum();

Code Explained

The method Reverse() reverses the list

The method Take() takes the specified number of items

The method Sum() performs the sum operation

Summary

In the above scenario, Lamba helped us from

1. Little hectic code of for loop and decrementing index
2. Reduced the number of lines from 3 to 1
3. Helped in attaining the functionality in ease

## One Line Lambda – To remove items in a list

Posted by Jean Paul on December 5, 2010

I would like to show the advantage of Lambda expressions in time and coding effort saving

Scenario

You are given a list of integers:

1

2

3

4

5

6

2

8

9

2

5

You need to remove the numbers 2 from the list:

The numbers are stored in IList<int> list;

Normal Approach

If you try to remove the object by using a foreach. It will result in the following exception.

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

foreach (int i in list)

if (i == 2)

list.Remove(i);

Error: Collection was modified; enumeration operation may not execute.

Another Approach

We can employ a while/for loop to achieve the same:

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

for(int i = 0; i < list.Count; i++)

if (list[i] == 2)

{

list.RemoveAt(i);

i–;

}

The code above works fine. But seeing the lambda approach below you can feel the reduced coding effort.

Lambda Approach

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

## list = list.Where(i => (i != 2)).ToList<int>();

// Here we are selecting the numbers which are not equal to 2 and

// converting the result into a new list

Output

The output of the application will be:

1

3

4

5

6

8

9

Note

Lambda Expressions are really powerful tool, which results in reduced code and saving time. It is really investing at the cost of just 10 minutes learning curve involved.

There are tons of fun code associated with Lambda Expressions awaiting you!!

## One Line Lambda – To remove items in a list

Posted by Jean Paul on December 5, 2010

I would like to show the advantage of Lambda expressions in time and coding effort saving

Scenario

You are given a list of integers:

1

2

3

4

5

6

2

8

9

2

5

You need to remove the numbers 2 from the list:

The numbers are stored in IList<int> list;

Normal Approach

If you try to remove the object by using a foreach. It will result in the following exception.

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

foreach (int i in list)

if (i == 2)

list.Remove(i);

Error: Collection was modified; enumeration operation may not execute.

Another Approach

We can employ a while/for loop to achieve the same:

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

for(int i = 0; i < list.Count; i++)

if (list[i] == 2)

{

list.RemoveAt(i);

i–;

}

The code above works fine. But seeing the lambda approach below you can feel the reduced coding effort.

Lambda Approach

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

## list = list.Where(i => (i != 2)).ToList<int>();

// Here we are selecting the numbers which are not equal to 2 and

// converting the result into a new list

Output

The output of the application will be:

1

3

4

5

6

8

9

Note

Lambda Expressions are really powerful tool, which results in reduced code and saving time. It is really investing at the cost of just 10 minutes learning curve involved.

There are tons of fun code associated with Lambda Expressions awaiting you!!

## How to map a command to method without using if/switch?

Posted by Jean Paul on November 26, 2010

Here I am trying to show the advantage of using Lambda expressions along with some built in delegates.

Scenario

The user will input a command like “MoveUp”, “MoveDown”, “TurnLeft”, “TurnDown”.  Based on the commands, you have to call the the methods MoveUp(), MoveDown(), TurnLeft(), TurnDown() respectively.

The old code will look like:

string command = "Move";

if (command == "MoveUp")

MoveUp();

else if (command == "MoveDown")

MoveDown();

else if (command == "TurnLeft")

TurnLeft();

else if (command == "TurnRight")

TurnRight();

We can replace the same code with Lambda and built-in delegate Action as:

string command = "Move";

IDictionary<string, Action> actions = new Dictionary<string, Action>();

actions.Where(a => a.Key == command).FirstOrDefault().Value();

Note: The Action is a built-in delegate with void as return and no arguments input.  There are total of 4 versions of Action.

## Speed of Lambda

Posted by Jean Paul on November 2, 2010

I have tried many Lambda expression evaluations and enjoyed the reduced coding efforts they provide. But really I would like to evaluate the speed benefits that Lambda provides. In this article I am trying to compare the speed difference of Lambda expressions with traditional programming. The results are mind-blowing.

Simple Scenario : Finding Sum

We have a list of ten thousand numbers and finding the sum n times. The loop will be going for n times each time incrementing the list count.  The sum method with Lambda Expression will be:

private decimal GetSum_Lambda()
{
return list1.Sum(); // Using pre-defined method
}

The core sum method without  Lambda Expression will be:

private decimal GetSum_WithoutLambda()
{
decimal sum = 0;
foreach (decimal d in list2)
sum += d;

return sum;
}

The output is graphically depicted as following. The red lines in x axis shows the processing time and y axis shows increasing complexity of the test.  Both test complexity are equally distributed.
The above test shows that Lamda expressions for the scenario is almost 50% faster. Not too much you might wonder â€“ I agree. But in the following test you will be seeing some surprising outputs.

Complex Scenario : Finding Distinct and then Sum

Shall we move towards a complex scenario?
Here the list has duplicate numbers. We need to remove the duplicate numbers and calculate the sum. This involves the following steps.
1. Remove the duplicates and create the new list
2. Find the sum from new list
The distinct and sum method with lambda expression looks like:
private decimal GetDistinctSum_Lambda()
{
return list1.Distinct().Sum();
}

The distinct and sum method without using lambda expression would be:
private decimal GetDistinctSum_WithoutLambda()
{
// Find Distinct
List<decimal> distinctList = new List<decimal>();
foreach (decimal number in list2)
if (!distinctList.Contains(number))

// Find Sum
decimal sum = 0;
foreach (decimal d in distinctList)
sum += d;

return sum;
}

The output is graphically depicted as following. Total Time for Lambda: 1 second
Total Time without Lambda: 11 seconds

From the above picture shows that Lambda expression is multiple times faster than the usual approach, as well it is memory efficient too.

Test Application
In the test application, both the simple and complex scenario can be tested using the combo box.
Click the Start button to start the computations. First the left panel computations are executed and then the right. Hope you can execute it.  Please let me know your suggestions or comments on the article.

Note

If we try many examples like this we can identify Lambda is having multiple time performance benefits than traditional programming. So I believe it is worth investing in Functional Programming in C# through Lambda Expressions. Happy Coding.

Posted in Lambda Expressions | Tagged: , , | 1 Comment »

## Delegates, Anonymous Methods, Lambda Expressions and Advantage, Built-in Delegates (Func, Action, Predicate), Examples

Posted by Jean Paul on October 19, 2010

The world have started moving from object oriented programming to functional programming.  The Lambda Expressions in C# is definitely providing many advantages like reduced code and speed above the traditional programming.  Learning Lambda Expressions and the built-in methods in C# is not too hard, but requires sincere efforts.

Power of Lambda

It is for sure that Lambda will reduce the code and execution time.

For example consider the case where a list contains numbers from 1 to 10, You wanted to print the numbers divisible by 2.

The code will be:

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

foreach(int number in list)

if ((number %2)== 0)

Console.WriteLine(number.ToString());

The same code for iterating, checking and displaying is combined using Lambda Expressions in one line as following:

list.Where(x => x > 0).ToList().ForEach(x => Console.WriteLine(x.ToString()));

Here we have reduced the code from 3 lines to 1 and the coding efforts too.  Above that, it is very interesting to use Lambda expressions.  Believe me!!

So I would like to start from the first step towards Lambda Expressions – that is delegates.  Learning one concept per day would be more easier and give more confidence in using it.

Delegates

Delegate is a type that references a method.  Same like a class variable can refer to an object instance, we can assign methods to the delegate variable.  It was a feature introduced in C# 2.0.

Example:

public delegate void SimpleDelegate();

static void Main(string[] args)

{

SimpleDelegate simpleDelegate = SimpleMethod;

simpleDelegate();

}

public static void SimpleMethod()

{

Console.WriteLine("Hi!");

}

We can use delegates to create a skeleton of a method that would be used by multiple classes.  Event handlers can be created using delegates.

Anonymous Methods

Anonymous methods were also introduced in C# 2.0 version.  Sometimes we run into cases like we have to create a method for assigning to events.  In this case, instead of creating a method, we can create inline methods – those are methods without a name.

Eg: In an ASP.NET application, we are setting the event handler of a button. The code will look like:

protected void Page_Load(object sender, EventArgs e)

{

Button button = new Button();

button.Click += new EventHandler(button_Click);

}

void button_Click(object sender, EventArgs e)

{

}

Here button_Click() is the method for the event handler.  The same code can be replaced as following using anonymous methods.

protected void Page_Load(object sender, EventArgs e)

{

button1.Click += delegate(object s1, EventArgs e1)

{

};

}

Please note that the delegate keyword is used to place the anonymous method.

In the above code we have saved one method and used inline coding for event handler.  This is a step towards our real aim – Lambda Expressions.

Delegates – Custom Delegate

Let us take another advanced example of Anonymous methods.  Here we are creating a custom delegate.  The WriteMessageDelegate delegate takes a string as argument and returns void.  It can be used as a callback mechanism to write messages globally in an application.

public class Operation

{

public delegate void WriteMessageDelegate(string write);

public void Do(WriteMessageDelegate write)

{

write("From Do() method.");

}

}

Test code is following: Here we are declaring a method named WriteMessage with same signature of the previous WriteMessageDelgate and then passing it to the Do method.

class Program

{

static void Main(string[] args)

{

Operation operation = new Operation();

operation.Do(WriteMessage); // See the method pointer we are passing

}

public static void WriteMessage(string message)

{

Console.WriteLine(message);

}

}

Please note that the Do method will be invoking the WriteMessage.

(One may get confused that statement operation.Do(WriteMessage); would be calling the WriteMessage. No!  This is just passing the method reference only)

If you can understand the above code, Congratulations!!!  You have just learned how to use delegates as arguments.

Lambda Expressions

A lambda expression is an anonymous function that can contain expressions and statements.

All lambda expressions uses the operator =>, which means “goes to”.

Eg: ForEach(argument => Console.WriteLine(argument));

The left hand side of => represents function arguments.

and the right hand side is the statement using argument.

Here the “argument” denotes the method argument and the operation on the right hand side.

This could be equivalent to the following lines:

public void Write(string argument)

{

Console.WriteLine(argument);

}

invoked as: list.ForEach(Write);

Example on Lambda

Consider we are having a list of string items.  We need to sort them using descending order.  So we have to implement the Compare() delegate.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

List<string> names = new List<string>();

names.Sort((s1, s2) => s2.CompareTo(s1)); // Sorting

names.ForEach(s => Console.WriteLine(s));

}

}

}

Note: All the examples are intended to have System.Linq in the namespace section.

Sorting Example

 Lambda Expression Without names.Sort((s1, s2) => s2.CompareTo(s1)); names.Sort(                 delegate (string s1, string s2)                 {                      return s2.CompareTo(s1);                   }              );

Integer OrderBy Example

 Lambda Expression Without names.OrderBy(s => int.Parse(s)); names.Sort(                 delegate (string s1, string s2)                 {                      return int.Parse(s2).CompareTo(int.Parse(s1));                   }              );

Note: The Sort() method actually changes the list, but OrderBy() gives an ordered view only without actually changing the list.

Integer OrderBy With Console Print

 using System.Linq; Namespace to include List list = new List(); list.Add("1"); list.Add("10"); list.Add("2"); Code to Arrange list.OrderBy(s => int.Parse(s)).ToList().ForEach(s => Console.WriteLine(s)); Lambda Code list.Sort(delegate(string s1, string s2) {     return int.Parse(s1).CompareTo(int.Parse(s2)); } );   foreach (string s in list)     Console.WriteLine(s); Regular Code

Selecting distinct Items With Console Print

 using System.Linq; Namespace to include List list = new List(); list.Add("1"); list.Add("1"); list.Add("2");  list.Add("2"); Code to Arrange list.Distinct(s => s).ToList().ForEach(s => Console.WriteLine(s)); Lambda Code IList unique = new List();             foreach (string s in list)                 if (!unique.Contains(s))                     unique.Add(s); foreach (string s in unique)     Console.WriteLine(s); Regular Code