Lambda expressions in c#

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 basic form of expression using lambda expression

1)      (input parameters) => expression: Here parenthesis are optional if there is only one parameter otherwise it is required.

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 represents lambda expression with collection

/// <summary>

        /// In this method we will see use of two method one is use of

        /// annoymouse method to search value in collection and other one

        /// is by using lambda expression to search. We see that using lambda

        /// expression line of code is saved.

        /// </summary>

        public void lambdaExpression()


            //Create a collection objects.

            List<string> nameCollection = new List<string>();

            //Add some values in collection object.






            //Using annoymouse expression for checking name

            string result = nameCollection.Find(delegate(string name)


                return name.Equals("John");


            if (!string.IsNullOrEmpty(result))



                Console.WriteLine("Specified record is not found.");

            //Using lambda expression for checking name

            string lambdaResult = nameCollection.Find(sname => sname.Equals("James1"));    //Here we directly write name of variable like sname.

            if (!string.IsNullOrEmpty(lambdaResult))



                Console.WriteLine("Specified record is not found.");


Leave Comment