TopMenu

What is Lambda Expression? A simple guide For beginners

Whenever we talk about LINQ then everything related to LINQ comes as a part of discussion and so the Lambda Expressions are. Sometimes people ask the question about the Lambda Expression; It look so weird why should I use it in my code and what exactly it stands for? Developers who either from C++ or working on C# 2.0 are still not have clear vision of Lambda Expression. What are Lambda Expressions?, When & Where to use them? These are the basic question that can comes in mind when anybody heard of new programming things.
Through this post I'll try to answer these question. There are new terms are being introduced with every release of .Net framework so lets get started with Lambda Expression for now:

What is 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:
delegate int anonymousDel(int i);
            anonymousDel myDelegate = new anonymousDel(
            delegate(int x)
            {
                return x * 2;
            });

            Console.WriteLine("{0}", myDelegate(5));

The segment inside the braces of anonymousDel is the also called as Anonymous Function.
Now lets convert it to Lambda Expression:
anonymousDel myDelegate = x => x * 2;

x => x * 2 is the Expression that is 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 holds the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no. of line as you can see and the output is still the same.

The above expression can be generalize for clear understanding.
(input parameters) => Expression;
and can be termed as "Expression Lambdas" since single Expression is involved here.
A Lambda Expression can contain multiple statements and can be surrounded by { } just like anonymous functions.
(input param1, input param2) => { statement1, Statement 2};
For e.g.
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
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 Lambda Expression like below:

delegate void doSomething();
           
doSomething IamVoid = () => { Console.WriteLine("Hello there! I take nothing and return nothing"
); };
           
//call the Anonymous function
            IamVoid();

When & Where to use Lambda Expression?
Whenever you came to know about new term and you already know what it is then directly ask yourself when & where it would be used. The Lambda Expressions can be used to  simply replacing the Anonymous functions, In the LINQ query methods, or any where you need to intialize Generic delegates.
LINQ Query example:

LINQ to Objects

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
           
int oddNumbers = numbers.Count(n => n % 2 == 1);

LINQ to SQL
Customers.Where(c => c.City == "London");

LINQ To XML
var xml1 = element.Descendants("customer").Where(cust => cust.Attribute("id").Value == CustomerId).SingleOrDefault();

OTHER
Func<>, Action<> and Expression<> are the new generic delgates where you can use Lambda Expressions. Don't panic with these new terms Lets take example where are these new generic delegates can be used.

Look at the below code snippet:

delegate int anonymousDel2(int a, int b);
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));

Lets modify the above code snippet using generic delegates and Lambda Expressions
Func<int, int, int> getBigInteger = (x, y) => { if (x > y) return x; else return y; };
           
Console.WriteLine(getBigInteger(10,15));

Explanation of Func<int, int, int> would be Func<parameter1, parameter2, returntype>
you can pass any number of argument but last mentioned type would be the type of returned value. Similary we use Action<param1, param2> in this we don't need to return any value. It denotes the Generic delegate here that have return type void. These delegates are introduced to provide the taste of Functional Progamming in the C# itself. if you are still interested in further reading then its worth for me writing this post.

When to use Lambda Expression?
Use whenever you feel reducing your line of code. Keep in mind the code maintainability while reducing the number of code lines. People think Lambda Expression as awkward looking code, But I'm telling you its worth using them in code wisely and once you understood the concept you'll fall in love using them. If you are going to use Excess of LINQ in your code then Lambda Expression will be your favorite buddy helping you wrap your code logic in few lines or may be Inline.

Hope you enjoyed reading this. Thanks for you time please leave comment for any question/suggestion.

34 comments:

  1. Like it... its very good for Linq beginners....

    ReplyDelete
  2. Thanks Kunal. It means a lot to me.. :)

    ReplyDelete
  3. Very good post, clarified some doubts I had. Thanks a lot.

    ReplyDelete
  4. very good introduction to lambda expressions.each step is well broken down with explanation.Thank you Michael G.

    ReplyDelete
  5. Very good...I was looking for this kind of easy intro.. Thanks a lot!.. Keep going...

    ReplyDelete
  6. Really good explanation thanks.

    ReplyDelete
  7. Simple explanation but covered lot of things...thanks,

    ReplyDelete
  8. Really very helpful lines. Amit Please give a print option in your website like www.codeproject.com and MSDN

    Thanks

    ReplyDelete
  9. Good and wisely written article. Now i will use them in my code.

    ReplyDelete
  10. Wonderful man...Covered almost everything in an easy to understand way. Thank you.

    ReplyDelete
  11. it is nice description about lambda
    THanks for this

    ReplyDelete
  12. That was a great explanation. However, if I could make a somewhat related suggestion for your code I would say that you should replace your if-else statements with the conditional ?: operator where you start with a boolean expression, and if it evaluates to true the first expression is evaluated, and if false the second expression is evaluated. It takes the form of

    (boolean statement) ? (Do this if true) : (do this if false);

    ReplyDelete
  13. Replies
    1. This comment has been removed by the author.

      Delete
    2. It is very hekpful to me to know about Lambda Expression.Thanks alot for ur post

      Delete
  14. Excellent article on Lamda Experssion..

    ReplyDelete
  15. Thanks alot it very helpful.

    ReplyDelete
  16. Lamba Expression using Anonymous type:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Linq_Basics
    {
    class Program
    {
    static void Main(string[] args)
    {

    string[] names = {"Amar","vicky","Bala","sankar","vimal" };

    var lambfilter = names.Select(c => new { Namelength = c.Length, Name = c });

    foreach (var v in lambfilter)
    {
    Console.WriteLine("The {0} name of length {1}",v.Name,v.Namelength);
    }

    Console.ReadKey();

    }
    }
    }

    ReplyDelete
  17. its very useful to all.thank u ........... then please provide the explanation about FirstOrdefault()

    ReplyDelete
  18. Nice explanation, I like it than you!!

    Anil SIngh
    http://www.code-sample.com/

    ReplyDelete