Introduction:

In this article we will learn, how to use LINQ Lambda expression or what is LINQ Lambda expression C# Asp.net Mvc with example.

Description:

LINQ Lambda expression:

 

In LINQLambda expression is an anonymous method that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

 

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type, as the following example shows:

LINQ Lambda Expressions Example:

Now we will give simple example to use lambda expressions.

 

using System;
using System.Collections.Generic;
using System.Linq;
namespace SQLTutorialsPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> countries = new List<string>();
            countries.Add("India");
            countries.Add("US");
            countries.Add("Nepal");
            countries.Add("Kanada");
            countries.Add("Russia");
            IEnumerable<string> result = countries.Select(x => x);
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

When we execute above c# program, we will get the result like as shown below.

how to use linq lambda expression in c#

In this example we have a List of type string that has countries stored in it. We use lambda expression to select the countries from the List<string> countries. Here Select is the property that we use to select from a List. And x is the input parameter that is on the left hand side of the expression followed by => operator. On the right hand side of the expression is the same input parameter which denotes that we just want to display the parameter without performing any operation on it. So we are not specifying any condition on it.

 

I hope it will help to you after reading.

 

 

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like