LINQ Lambda Expressions

In Linq, a function without a name is known as Lambda expression. It a more clear and makes the syntax small. As lambda expression is not must readable but internally its get converted to lambda only.

Syntax of LINQ Lambda Expressions

(parameter) => any expression

Lambda expression is dynamic in nature and defines the type during compile time. We can make lambda expression by the combination of Equals ( = ) and greater than sign ( > ) i.e => 

For example m => m + 20

Here, on the left-hand side is the input parameter followed by lambda sign => and then the expression is written. So the output is will be 20.

Example Code:

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

namespace LinqDemoes
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> state = new List<string>();
            state.Add("Surat");
            state.Add("Ahmedabad");
            state.Add("Gandhinagar");
            state.Add("Rajkot");
            IEnumerable<string> result = state.Select(x => x);
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

Here, we have a list type of string and we have stored them in state variable and we have select all the states from the list.

Output:

Surat
Ahmedabad
Gandhinagar
Rajkot

Now we will find odd and even numbers using the Linq lambda expression

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

namespace LinqDemoes
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 50,25,12,63,45,98,63,52,47,52 };
            Console.WriteLine("Even numbers");
            IEnumerable<int> even = numbers.Where(x => x % 2 == 0);
            foreach (var item in even)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("--------------------------------------------------");
            Console.WriteLine("Odd numbers");
            IEnumerable<int> odd = numbers.Where(x => x % 2 != 0);
            foreach (var item in odd)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

Output:

Even numbers
50
12
98
52
52
--------------------------------------------------
Odd numbers
25
63
45
63
47

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories