Lambda Expression in 15 Minutes

This is very short and quick article to demonstrate various uses of lambda expressions in C#.

This is a very short and quick article to demonstrate various uses of lambda expressions in C#. I believe lambda expressions is one of the nicest features introduced in C# 3.0.

So let's start with a little theory and then we will get to a practical session.

What lambda expressions are

A lambda expression is an anonymous function and it is usually used to create delegates in LINQ. Simply put, it's a method without a declaration; in other words, an access modifier, a return value declaration and a name.

Fine, so a lambda expression is nothing but an anonymous function that doesn't have a name, just an input and output, that's all.

If it is not reusable, why use it?

Generally, the question may arise, if the function doesn't have a name, then it's not reusable anywhere. Which is not a good idea in terms of good development practices. Yes I agree but there are specific situations where lambda expressions can perform a smart role. We will figure out the situation where lambda expressions can perform better.

How it works

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator => and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that's named x and returns the value of x squared and the number of inputs may be any number.

Show me one example

Yes, I too want an example. Here is a simple example of a lambda expression. You may think, why do I have (and many) an attached lambda expression with delegates? The reason is simple, as we know a lambda expression is nothing but an anonymous function and delegates know how to handle a function, since it is nothing but a function pointer. So, generally when we want to implement an anonymous function, we need to ensure someone is pointing to the function.
  1. class Program  
  2.  {  
  3.      delegate Boolean mydel(int data1,int data2);  
  4.      static void Main(string[] args)  
  5.      {  
  6.          mydel d = (x,y) => x>y;  
  7.          Console.WriteLine(d(10, 20));  
  8.          Console.ReadLine();  
  9.      }  
  10.  } 

Otherwise we cannot invoke the function in the future. So, let's understand the example. As we said, a lambda expression has only an input and output as in the following:

  1. mydel d = (x,y) => x>y;  
  2. Console.WriteLine(d(10, 20)); 

X and Y are the input and output boolean values, the expression pattern is such that we have attached it with the same type of delegate.

Here is sample output.



Expression lambda

If the right side of a lambda expression carries an expression tree then this kind of lambda expression is called an expression lambda. Yes, the example that we have see just now is one example of an expression lambda. Here is another one.

  1. class Program  
  2.     {  
  3.         delegate int mydel(int data1,int data2, int data3);  
  4.         static void Main(string[] args)  
  5.         {  
  6.             mydel d = (x, y ,z) =>  (x > y == true) ? (x > z == true) ? x : z : (y> z == true)? y:z;  
  7.             Console.WriteLine(d(50,60,30));  
  8.             Console.ReadLine();  
  9.         }  
  10.     } 

Yes, we should not write this kind of logic in a real application, it may cause frustration for someone else. In this example we have implemented the three number comparison algorithyms in a single line lambda expression. So, have a look at the right side and you will find a big expression.



Statement lambda

A statement lambda will contain a statement in the right hand side of the lambda expression. Have a look at the following example.

  1. class Program  
  2.     {  
  3.         delegate void mydel();  
  4.         static void Main(string[] args)  
  5.         {  
  6.             mydel d = () => Console.WriteLine("Statement lambda");  
  7.             d.Invoke();  
  8.             Console.ReadLine();  
  9.         }  
  10.     } 

Here we have invoked the Console.WriteLine() function by a delegate using a lambda expression. Here is the output.



It's not that a statement lambda can execute one and only one statement. We can execute multiple statements too. Have a look at the following example.

  1. public class test  
  2. {  
  3.     public static void hello()  
  4.     {  
  5.         Console.WriteLine("I am hello function");  
  6.     }  
  7. }  
  8. class Program  
  9. {  
  10.     delegate void mydel();  
  11.     static void Main(string[] args)  
  12.     {  
  13.         mydel d = () => {  
  14.             Console.WriteLine("I am first statement");  
  15.             test.hello();  
  16.         };  
  17.         d.Invoke();  
  18.         Console.ReadLine();  
  19.     }  

Here the pattern of both Console.WriteLine() and fun() are the same so that we have attached both in the same delegate and invoked it. Here is sample output.



Lambda expression with Func

A Lambda expression fits sweetly with a Func. We know that a Func is an anonymous delegate and we can attach an anonymous function to it. Since a lambda expression is nothing but a function, we can attach it with the Func . In the following example we will attach a lambda expression with fun anonymous delegates.

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Func<intint, Boolean> fun = (x, y) => x > y;  
  6.         Console.WriteLine(fun(10, 10));  
  7.         Console.ReadLine();  
  8.     }  

Here is sample output.



Lambda expression fit nice with collection

Yes, the real use of a lambda expression is with a collection. It's very handy to sort and/or shuffle a collection using a lambda expression. Here are a few examples.

 

  1. class person  
  2. {  
  3.     public string name { getset; }  
  4. }  
  5. class Program  
  6. {  
  7.     static void Main(string[] args)  
  8.     {  
  9.         int[] data = { 1, 2, 4, 5, 6, 10 };  
  10.         //find all even number from array  
  11.         int[] even = data.Where(fn => fn % 2 == 0).ToArray();  
  12.   
  13.         //find all odd number from array  
  14.         int[] odd = data.Where(fn => fn % 2 != 0).ToArray();  
  15.   
  16.         List<person> persons = new List<person> {   
  17.             new person {name = "Sourav"},  
  18.             new person {name = "Sudip"},  
  19.             new person {name = "Ram"}  
  20.         };  
  21.   
  22.         //List of person whose name starts with "S"  
  23.         List<person> nameWithS = persons.Where(fn => fn.name.StartsWith("S")).ToList();  
  24.         Console.ReadLine();  
  25.     }  

Lambda expression in async

I hope you know the concept of Asynchronous programming in C# 5.0. Asynchronous programming is the updated version of multithreading in C#, anyway let's see how to use a lambda expression to execute a task asynchronously. Have a look at the following example.

  1. namespace Client  
  2. {  
  3.     public class AsyncClass  
  4.     {  
  5.         public async Task<string> Hello()  
  6.         {  
  7.            return await Task<string>.Run(()=>{  
  8.                return "Return From Hello";  
  9.            });  
  10.         }  
  11.         public async void fun()  
  12.         {  
  13.             Console.WriteLine(await Hello());  
  14.         }  
  15.     }  
  16.   
  17.     class Program  
  18.     {  
  19.         static void Main(string[] args)  
  20.         {  
  21.             new AsyncClass().fun();  
  22.             Console.ReadLine();  
  23.         }  
  24.     }  

And here is the output. In this example we are returning a string but if needed we can return any type of data.



Let's use an anonymous function and async together

Here we will modify the previous example a little bit. We will now execute the function using a lambda expression asynchronously. Have a look at the following example.

  1. namespace Client  
  2. {  
  3.     public class AsyncClass  
  4.     {  
  5.         public string Hello(string name)  
  6.         {  
  7.             return name;  
  8.         }  
  9.   
  10.         public async Task<string> Hello()  
  11.         {  
  12.            return await Task<string>.Run(()=>{  
  13.                //lambda expression to execute function using Func anonymous delegate  
  14.                Func<stringstring> del = x => x;  
  15.                return del.Invoke("sourav");  
  16.            });  
  17.         }  
  18.         public async void fun()  
  19.         {  
  20.             Console.WriteLine(await Hello());  
  21.         }  
  22.     }  
  23.   
  24.     class Program  
  25.     {  
  26.         static void Main(string[] args)  
  27.         {  
  28.             new AsyncClass().fun();  
  29.             Console.ReadLine();  
  30.         }  
  31.     }  

Here is the output.



Conclusion

Now, let's understand why to use a lambda expression and in which scenario they fit. We have seen that a lambda expression can replace anonymous functions and make the code size short but it's always recommended to use a lambda expression in a simple way, because it reduces code readability.

So, use a lambda expression when it's necessary to implement something simple and it is not necessary to use it more than once in the application.