C# Lambda Expressions

Updated on     Kisan Patel

In .Net Framework, a new syntax, named Lambda expressions, was introduced for anonymous methods. A Lambda expression is an anonymous function that can contain expressions and statements to create delegates or expression tree types.

Lambda expressions are specified as a comma-delimited list of parameters followed by the lambda operator, followed by an expression or statement block. In C#, the lambda operator is =>.

If there is more than one input parameter, enclose the input parameters in parentheses.

Syntax

(param1, param2, …paramN) => expr

For Example,

x => x.Length > 0

This lambda expression could be read as “input x returns x.Length > 0.”.

If multiple parameters are passed into the lambda expression, separate them with commas, and enclose them in parentheses like this.

(x, y) => x == y

C# can define an anonymous delegate in an easier way, using a lambda expression. Using a lambda expression, you can rewrite the filtering code more compactly.

For Example,

string[] names = { "Kisan", "Devang", "Ravi", "Ujas", "Karan" };
var filteredName = names.Where (n => n.Contains ("K"));

Here, Where is an extension methods. The Select statement is also an extension method provided by the Enumerable class.

For Example,

string[] names = { "Kisan", "Devang", "Ravi", "Ujas", "Karan" };
var filteredName = names
                      .Where (n => n.Contains ("K"))
                      .Select (n => n.ToUpper());
Note : In Lambda expressions, an expression that return a bool value is called a predicate.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Kisan", "Devang", "Ravi", "Ujas", "Karan" };

            IEnumerable query = names
                      .Where(n => n.Contains("K"))
                      .Select(n => n.ToUpper());

            foreach (var name in query)
                Console.WriteLine(name);
        }
    }
}

the output of the above C# program…

linq-lamda-expressions-demo

Advantages of Lambda queries

  • Generally offer more control and flexibility.
  • Chaining of query operators looks like a pipeline.
  • Select operator is optional (when not doing a projection).
  • Many query operators have no comprehensive query equivalent.

C# LINQ

Leave a Reply