Wednesday 21 August 2013

Lambda expression in Linq.

Lambda expression is one of the features introduced in c# 3.0. Lambda expression helps you to ease the burden of verbose of anonymous functions or methods.

Lambda expression is anonymous function or method that you can use to create delegates or expression tree type. Lambda expressions use lambda operator i.e =>.

Lambda expression:-

      x => x*x;

  •     The left hand side of operator specified input parameter.
  •     The right hand side of operator is expression or statement.


In the above lambda expression , x on the left hand side is input parameter and the right hand side is expression that return the result of value (x*x) of input x.


Let see the below example to better understand of lambda expression.

In this example lambda expression, with collection to find out employee details using empId.

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

namespace LambdaInLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            EmpDetails empDetail = new EmpDetails();
            clsEmployee empDetails = empDetail.FindEmpById("EMP1");
            if (empDetails == null)
            {
                Console.WriteLine("Emp does not exist.");
            }
            else
            {
                Console.WriteLine("Name:"+empDetails.EmpName);
                Console.WriteLine("ID:" + empDetails.EmpId);
                Console.WriteLine("DOB:" + empDetails.DOB);
                Console.WriteLine("DOJ:" + empDetails.DOJ);
            }
            Console.ReadLine();
        }
        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> listEmp = new List<clsEmployee>();
            //initializing the details using constructor
            public EmpDetails()
            {
                AddEmpDetails();
            }
            //adding the employee details in listEmp
            public void AddEmpDetails()
            {
                listEmp.Add(new clsEmployee { EmpId = "EMP1", EmpName = "Sushil", DOB = DateTime.Now.Date.AddYears(-20) });
                listEmp.Add(new clsEmployee { EmpId = "EMP2", EmpName = "Ashu", DOB = DateTime.Now.Date.AddYears(-21) });
                listEmp.Add(new clsEmployee { EmpId = "EMP3", EmpName = "Sanjay", DOB = DateTime.Now.Date.AddYears(-35) });
            }
            // method to find employee Details in listemp using Lambda expression
            public clsEmployee FindEmpById(string EmpId)
            {
                return listEmp.Find(m => m.EmpId == EmpId);
            }
        }
       
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.