May 12, 2013

Lambda expression in C#

In this post, I am explaining what is Lambda Expression in C# and how to use it.

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. All Lambda expressions use lambda operator =>.
  • The left hand side of operator specified input parameter (if any)
  • Expression or statement is written on the right side of the operator
Lambda expression
x => x*x;
In the above Lambda expression, "x" on the left side is input parameter and on the right side is expression that returns the square value (x*x) of input "x".

Now lets take some example to understand more clearly how Lambda expressions are used

Example: Using Lambda Expression with List to find out if input name exists in List
List<string> listNames = new List<string>();
string result = listNames.Find(name => name.Equals("sandeep"));
Example: Using Lambda expression, with collection to find out employee details passing Employee ID
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            EmpDetails empDetails = new EmpDetails();
            clsEmployee empDetail = empDetails.FindEmpByID("EMP001");
            if (empDetail == null)
                Console.Write("Employee does not exist");
                Console.Write("Emp ID : " + empDetail.EmpId);
                Console.Write( "\nEmp Name : " + empDetail.EmpName);
                Console.Write("\nEmp DOB : " + empDetail.DOB.ToString("dd/MM/yyyy"));

        public class clsEmployee
            public string EmpId { get; set; }
            public string EmpName { get; set; }
            public DateTime DOB { get; set; }
            public DateTime DOJ { get; set; }

        public class EmpDetails
            //Creating object
            List<clsEmployee> listEmpCollection = new List<clsEmployee>();

            //Initializing Employee Details using constructor
            public EmpDetails()

            //Adding Employee details in the employees listEmpCollection

            private void AddEmpDetails()

                listEmpCollection.Add(new clsEmployee { EmpId = "EMP001", EmpName = "Sandeep", DOB = DateTime.Now.Date.AddYears(-28) });
                listEmpCollection.Add(new clsEmployee { EmpId = "EMP002", EmpName = "Abhay", DOB = DateTime.Now.Date.AddYears(-26) });
                listEmpCollection.Add(new clsEmployee { EmpId = "EMP003", EmpName = "Ritesh", DOB = DateTime.Now.Date.AddYears(-25) });

            //Method to find the Employee details by pasing Emp Id using Lambda expression
            public clsEmployee FindEmpByID(string EmpId)
                return listEmpCollection.Find(m => m.EmpId == EmpId);

    Choose :
  • OR
  • To comment
No comments:
Write Comments