Lambda Expression in C#

In this article, we will discuss the Lambda expression in C#, with the help of quite a good coding example we will see how to implement lambda in C#. Anonymous functions called lambda expressions which can contain expressions or a series of operators. All lambda expressions use the lambda operator =>, which can be read as “goes to” or “becomes”. The lambda operator's right side contains an expression or a code block that interacts with the entry parameters, while the left side defines the input parameters. Usually, lambda expressions are used as predicates or instead of delegates (a type that references a method).


The lambda expression can be of two types:

  1. Statement Lambda     2) Expression Lambda


Statement Lambda:


Consists of the input and a set of statements to be executed.

Syntax:


input => { statements };



Note: It does not return any value implicitly.

Given below is an example of statement lambda implementation.



namespace LambdaExpression

{

    public delegate int MyDelegate(int num1, int num2);

    class Program

    {

        static void Main(string[] args)

        {

       

           

            MyDelegate obj = (a, b) =>

            {

               

                return a+b;

            };

            Console.WriteLine("The result is: " +obj.Invoke(10, 20));

            Console.ReadLine();

        }

    }

}




Output:


The result is: 30




Expression Lambda:


Consists of the input and the expression.

Syntax:

input => expression;


Note: Returns the evaluated value implicitly.


Below is an example of expression lambda implementation.


namespace LambdaExpression

{

    public delegate int MyDelegate(int num1, int num2);

    class Program

    {

        static void Main(string[] args)

        {

            MyDelegate obj = (a, b) => a + b;

            Console.WriteLine("The result is: " +obj.Invoke(10, 20));

           

            Console.ReadLine();

        }

    }

}



Output:


The result is: 30




Query Parameters in C# Lambda Expressions:


In LINQ to Objects and other implementations, input parameters from the Func<TResult> family of generic delegates are utilized. Type parameters in these delegates specify the quantity and nature of the input arguments as well as the delegate's return type. func delegates contain user-defined expressions that are applied to every element in a collection of source data. Take the delegate type Func<T,TResult> for example:


public delegate TResult Func<in T, out TResult>(T arg)




Use of COUNT in Lambda:


We can provide a Lambda Expression where the argument type is an ExpressionTDelegate>, like in the case of the Standard Query Operators specified in the Queryable type. The Lambda is usually compiled into an expression tree when you use the Expression<TDelegate> Parameter.


The following example uses the Count Standard Query Operator:



namespace LambdaExpression

{

    class Program

    {

        static void Main(string[] args)

        {

         

            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

            int oddNumbers = numbers.Count(n => n % 2 == 1);

            Console.WriteLine($"There are {oddNumbers} odd numbers in {string.Join(" ", numbers)}");

            Console.ReadLine();

        }

    }

}




Output:


There are 5 odd numbers in 5 4 1 3 9 8 6 7 2 0



The type of an input parameter can either be explicitly defined or inferred by the compiler. This Lambda Expression determines how many integers (n) divide by 2 with a remainder of 1.



Sorting values using Lambdas:


Sorts the collection based on specified fields in descending order. Only valid in method syntax.

An example of sorting with a Lambda Expression is as follows:


namespace LambdaExpression

{

    class Person

    {

        public string Name { get; set; }

        public int Age { get; set; }

    }

    class Program

    {

       

        static void Main(string[] args)

        {

   

            List<Person> people= new List<Person>() {

         new Person { Name = "roman", Age = 40 },

         new Person { Name = "david", Age = 25 },

         new Person { Name = "jack", Age = 30 }

      };

            var sortedPerson = people.OrderByDescending(x => x.Age);

            foreach (var boy in sortedPerson)

            {

                Console.WriteLine(string.Format("Boy {0} is {1} years old.", boy.Name, boy.Age));

            }

            Console.ReadLine();

        }

    }

}



Output:


 Boy roman is 40 years old.

 Boy david is 25 years old.

 Boy jack is 30 years old.




Use of orderby in  Lambda:


Sorts the elements in the collection based on specified fields in ascending or descending order.

Given below is an example of orderby.


namespace LambdaExpression

{

    class Program

    {

       

        static void Main(string[] args)

        {

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

            list.Add("mississippi"); // Longest.

            list.Add("indus");

            list.Add("danube");

            list.Add("nile"); // Shortest.

           


 var lengths = list.OrderBy(x => x.Length)

                         

            foreach (string value in lengths)

            {

                Console.WriteLine(value);

            }

            Console.ReadLine();

        }

    }

}


Output:

 nile

 indus

 danube

 mississippi



Use of SELECT in Lambda:


The Select operator always returns an IEnumerable collection that contains elements based on a transformation function.

Given below is an example of select.


List<Dog> dogs = new List<Dog>() {  

  new Dog { Name = "Rex", Age = 4 },  

  new Dog { Name = "Sean", Age = 0 },  

  new Dog { Name = "Stacy", Age = 3 }  

};  

var names = dogs.Select(x => x.Name);  

foreach (var name in names)  

{  

   Console.WriteLine(name);

}

Console.ReadLine();



Output:

 Rex

 Sean

 Stacy



Using Lambda Expressions with Anonymous Types:


The select operator can be used to formulate the result as per our requirement. It can be used to return a collection of custom class or anonymous type which includes properties as per our need.

Given below is an example of anonymous types.


List<Dog> dogs = new List<Dog>() {

  new Dog { Name = "Rex", Age = 4 },

  new Dog { Name = "Sean", Age = 0 },

  new Dog { Name = "Stacy", Age = 3 }

};

           

            var names = dogs.Select(x => new { Age = x.Age, FirstLetter = x.Name[0] });

            foreach (var name in names)

            {

                Console.WriteLine(name);

            }

                Console.ReadLine();



Output:

 

 { Age = 4, FirstLetter = R }

 { Age = 0, FirstLetter = S }

 { Age = 3, FirstLetter = S }




Use of WHERE in Lambda:


Returns values from the collection based on a predicate function.

Given below is an example of where.


 List<Student> student = new List<Student>() {

  new Student { Name = "Rex", Age = 24 },

  new Student { Name = "Sean", Age = 20 },

  new Student { Name = "Stacy", Age = 18 },

  new Student { Name = "jack", Age = 13 },

  new Student { Name = "David", Age = 23 }

 };

           

 var x = student.Where(s => s.Age > 12 && s.Age < 20 );  


 foreach (var records in x)

 {

 Console.WriteLine(records.Name);

 }

    Console.ReadLine();




Output:

 Stacy

 Jack





Use of FIND in Lambda:


Given below is an example of find.


List<int> list = new List<int>(new int[] { 19, 23, 29 });

       

        // Finds first element greater than 20.

        int result = list.Find(item => item > 20);

       

        Console.WriteLine(result);  




Output:


 23



Use of SUM in Lambda:


The Sum() method calculates the sum of numeric items in the collection.

The following example demonstrates Sum() on primitive collection.


 

 IList<int> intList = new List<int>() { 10, 21, 40, 55, 60, 87 };

 var total = intList.Sum();

 Console.WriteLine("Sum: {0}", total);

 var sumOfEvenElements = intList.Sum(i => {

                          if(i%2 == 0)

                            return i;

     

                          return 0;

                            });

 Console.WriteLine("Sum of Even Elements: {0}", sumOfEvenElements );




Output:

 

Sum: 273

 Sum of Even Elements: 110




Use of Min and MAX in Lambda:


The Max() method returns the largest numeric element from a collection.

The following example demonstrates Max() on primitive collection.


IList<int> intList = new List<int>() { 9,10, 21, 40, 55, 60, 87 };


var largest = intList.Max();

Console.WriteLine("Largest Element: {0}", largest);


var largestEvenElements = intList.Max(i => {

                              if(i%2 == 0)

                                return i;

     

                              return 0;

                            });


Console.WriteLine("Largest Even Element: {0}", largestEvenElements );




//--------use of min method-------


var smallest = intList.Min();

Console.WriteLine("Smallest Element: {0}", smallest);


var smallestEvenElements = intList.Min(i => {

                              if(i%2 == 0)

                                return i;

     

                              return 0;

                            });


Console.WriteLine("Smallest Even Element: {0}", smallestEvenElements);



Output:


Largest Element: 87

Largest Even Element: 60


Smallest Element: 9

Smallest Even Element: 10




Conclusion:


In this article, we learned how to use the C# Lambda function in many Use Cases. We gained a deep understanding of the various scenarios you could run into when utilizing the C# Lambda function. The latest updates to.NET and.NET Core include the fantastic new feature of lambda expressions. Lambda expressions can have 0 arguments, 1 argument, or more arguments.

hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.




Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee