Home > DeveloperSection > Blogs > Introduction of Lambda Expression.

Introduction of Lambda Expression.


C# C# 
Ratings:
0 Comment(s)
 3969  View(s)
Rate this:

Introduction of Lambda Expression in C#


In this blog I am going to explain you that how to use Lambda expression in c# or what benefits we will get using lambda expression. After reading this blog you understand when to use lambda expression.

Most important thing about lambda expression is that, your code is shorter and looking attractive. I am frequently using lambda expression in my codes. You can use lambda expression with any type of collection which user defined collection also. Using lambda expression is very simple. Here I will tell you that how to use lambda expression with generic collection.

Lambda expression is also known as magical expression as it automatically knows what next you have to do. We use => symbol or operator to use lambda expression.

A lambda expression is an anonymous function that can contain expressions and statements and can be used to create delegates or expression tree type. All lambda expressions use the lambda operator =>, which is read as �goes to�. The left side of lambda operator specifies the input parameter if any and right side holds the expression or statement block.

The lambda expression has the same precedence as assignments (=) and is right associative. We can use lambdas in method based LINQ query as argument to slandered query. We cannot use lambda operators on the left side of is or as operator.

We can use following basics form of expression while using lambda expression

1)      (Input parameters) => Expression (Here parameters are optional.)

2)      (x , y) => x == y (We can use this type of lambda expressions when we want to specify input types to the compiler.)

3)      ( ) => SomeMethod(): When we want to create expression trees such as with sql server function then we use these type of lambda expression.

Example which represent�s use of lambda expression with collection

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DataGridViewDemo

{

    /// <summary>

    /// Create a user defined datatype of EmployeeDetails

    /// We use this datatype to add values in collection

    /// which is of type List<EmployeeDetails>

    /// </summary>

    public class EmployeeDetails

    {

        public int EmployeeID { get; set; }

        public string EmployeeName { get; set; }

        public DateTime BithDate { get; set; }

    }

    public class LambdaExpressionDemo

    {

        /// <summary>

        /// Create an object of List<EmployeeDetails> collection.

        /// </summary>

        List<EmployeeDetails> lstEmployeeCollection = new List<EmployeeDetails>();

        /// <summary>

        /// We can add employee details in lstEmployeeCollection

        /// using this method.

        /// </summary>

        public void addEmployeeDetails()

        {

            lstEmployeeCollection.Add(new EmployeeDetails

            {

                EmployeeID = 1,

                EmployeeName = "Awadhendra",

                BithDate = DateTime.Now.AddYears(-24)

            });

            lstEmployeeCollection.Add(new EmployeeDetails

            {

                EmployeeID = 2,

                EmployeeName = "Abhishek",

                BithDate = DateTime.Now.AddYears(-22)

            });

            lstEmployeeCollection.Add(new EmployeeDetails

            {

                EmployeeID = 3,

                EmployeeName = "Atul",

                BithDate = DateTime.Now.AddYears(-20)

            });

            lstEmployeeCollection.Add(new EmployeeDetails

            {

                EmployeeID = 4,

                EmployeeName = "Nidhi",

                BithDate = DateTime.Now.AddYears(-24)

            });

            lstEmployeeCollection.Add(new EmployeeDetails

            {

                EmployeeID = 5,

                EmployeeName = "Nikita",

                BithDate = DateTime.Now.AddYears(-20)

            });

        }

        /// <summary>

        /// In this method we will use lambda expression to

        /// find employee details of perticular id.

        /// </summary>

        /// <param name="EmployeeID">EmployeeId will be supllied by user.</param>

        public void FindEmployeeById(int EmployeeID)

        {

            EmployeeDetails empDetails = lstEmployeeCollection.Find(m => m.EmployeeID == EmployeeID);

            if (empDetails == null)

                Console.WriteLine("Employee Id does not exists.");

            else

            {

                Console.WriteLine("Employee Id : " + empDetails.EmployeeID);

                Console.WriteLine("Employee Name : " + empDetails.EmployeeName);

                Console.WriteLine("Employee Birth Date : " + empDetails.BithDate);

            }

        }

        /// <summary>

        /// Here in this method we will find all employees whose birth date is

        /// greater than given date using lambda expression.

        /// </summary>

        /// <param name="empDate"></param>

        public void FindAllEmployee(DateTime empDate)

        {

            List<EmployeeDetails> findEmployee = lstEmployeeCollection.FindAll(m => m.BithDate < empDate).ToList();

            if (findEmployee == null || findEmployee.Count == 0)

                Console.WriteLine("No employee details exists of given date.");

            else

                Console.WriteLine("Employee Details exists.");

        }

    }

}

Thanks for reading this blog. Please write your valuable comments.


Don't want to miss updates? Please click the below button!

Follow MindStick