Beginners Guide To Lambda Expressions

I recently attended a session on LINQ where everything related to LINQ had been the part of discussion, including Lambda Expressions and after feeling of expressing my views I came to write this post. Developers who are either from C++ or working on C# 2.0 still might not have a clear vision of Lambda Expressions. What are Lambda Expressions?, When & Where to use ?, Why to use ? These are the basic question that can come to mind when anybody hears of new programming things. Through this post I'll try to answer these question. There are new terms that are being introduced with every release of .Net framework, so lets get started with Lambda Expression for now,
 

What is a Lambda Expression?

 
Lambda expressions are similar to anonymous methods introduced in C# 2.0, except that lambda expressions are more concise and more flexible. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.
 
Lets take an example,
  1. delegate int anonymousDel (int i);  
With C# 2.0, anonymous methods allow you to write a method and initialize a delegate in place,
  1. anonymousDel myDelegate = new anonymousDel(  
  2. delegate(int x)  
  3. {  
  4.     return x * 2;  
  5. });  
  6.   
  7. Console.WriteLine("{0}", myDelegate(5));  
The segment inside the braces of anonymousDel is also called as Anonymous Function. Now lets convert it to a Lambda Expression,
  1. anonymousDel myDelegate = x => x * 2;  
x => x * 2 is the expression that is the known as Lambda Expression. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side hold the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no. of lines as you can see and the output is still the same. The above expression can be generalized for clearer understanding.
  1. (input parameters) => Expression;  
and can be called as "Expression Lambdas" since single Expression is involved here. It can contain multiple statements and can be surrounded by { } just like anonymous functions.
  1. (input param1, input param2) => { statement1, Statement 2};  
  2.   
  3.         for e.g. delegate int anonmousDel2(int a, int b);  
  4.         anonmousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };  
  5.         Console.WriteLine(getBigInteger(10,15));  
You can raise a question here, how x & y are being treated as integer while you didn't declared them as integer? Here is the answer. When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as described in the C# Language Specification. Anonymous function that take no parameter and return nothing can be written in form of a Lambda Expression like below,
  1. delegate void doSomething();  
  2. doSomething IamVoid = () => { Console.WriteLine("Hello there! I take nothing and return nothing"); };  
  3.     //call the Anonymous function  
  4.     IamVoid();  

When & Where to use Lambda Expressions?

 
Whenever you came to know about a new term and you have learned what it is, then you ask yourself when & where it would be used. Lambda Expressions can be used to simply replacing Anonymous functions, In the LINQ query methods, or anywhere you have to initialize Generic delegates. LINQ Query example: LINQ to Objects
  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };  
  2. int oddNumbers = numbers.Count(n => n % 2 == 1);  
LINQ to SQL
  1. Customers.Where(c => c.City == "London");  
LINQ To XML
  1. var xml = element.Descendants("customer").Where(cust => cust.Attribute("id").Value == CustomerId).SingleOrDefault();  
Func<>, Action<> and Expression<> are the new generic delegates where you can use Lambda Expressions. Don't panic with these new terms. Lets look at an example where these new generic delegates can be used. See the below code snippet,
  1. delegate int anonmousDel2(int a, int b);  
  2. anonmousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };  
  3. Console.WriteLine(getBigInteger(10,15));  
Lets modify this using generic delegates and Lambda Expressions,

  1. Func<intintint> getBigInteger;  
  2. getBigInteger = (x, y) => { if (x > y) return x; else return y; };  
  3. Console.WriteLine(getBigInteger(10,15));  
Explanation Func<int, int, int> of would be,
 
Func<parameter1, parameter2, returntype> You can pass any number of arguments but the last mentioned type would be the type of returned value. Similary we use Action<param1, param2> in this because we don't need to return any value. It tells the Generic delegate that you have a return type of void. These delegates were introduced to provide a taste of Functional Progamming in C# itself. if you are still interested in reading further into it then its worth it for me writing this post.
 

When to use Lambda Expressions?

 
Use them whenever you feel you can reduce your lines of code. Keep in mind the maintainability while reducing the number of lines of code. People think that Lambda Expressions are awkward looking code, but I'm telling you its worth it to use them in code wisely. Once you understood the concept you'll love it. If you are going to use excess of LINQ in your code then Lambda Expressions will be your favorite buddy. Helping you wrap your code logic in fewer lines or maybe InLine.


Similar Articles