| by Arround The Web | No comments

C# LINQ Lambda Expressions

Lambda expression in C# directly takes the expressions/conditional statements as its body without name. We need to specify the parameters and then the expressions are assigned to it. While working with Language Integrated Query (LINQ), you may have a requirement that you need to transform the data that is present in the data source or convert one data source to another data source.  In this guide, we will see how to filter the records from the data source by specifying the lambda expression and select the records from the data source.

Syntax:

  1. Lambda Expression: (parameters) => expression
  2. Lambda Statement: { conditional statement1 statement2 … }

Example 1:

Create the “fertilizers” list that holds five strings. Utilize the lambda expression that returns all the strings from the list.

using System;
using System.Linq;
using System.Collections.Generic;

 class LambdaExpressionExample {

    static public void Main()
    {

        // Create List of fertilizers
        List fertilizers = new List();  
        fertilizers.Add("Urea");  
        fertilizers.Add("nitrogen");  
        fertilizers.Add("potassium");  
        fertilizers.Add("Di-ammonium Phosphate");
        fertilizers.Add("phosphorus");
       
        // Use LambdaExpression to select all the fertilizers
        var result = fertilizers.Select(inp1 => inp1);  
        foreach (var i in result)  
        {  
            Console.WriteLine(i);  
        }  

    }
}

Output:

Explanation: 

1. Create list of string type named “fertilizers”. Add five strings to this list.

2. Use the lambda expression to select all the fertilizers. Here, the expression is used with the “Select” operator. The expression is inp1 => inp1. Then, we use the “foreach” loop to display the strings that are returned by the lambda expression.

Example 2:

Use the lambda expression to select the fertilizers that include “Phosphate”.

using System;
using System.Linq;
using System.Collections.Generic;

 class LambdaExpressionExample {

    static public void Main()
    {

        // Create List of fertilizers
        List fertilizers = new List();  
        fertilizers.Add("Urea");  
        fertilizers.Add("nitrogen");  
        fertilizers.Add("ortho - Phosphate ");  
        fertilizers.Add("Di-ammonium Phosphate");
        fertilizers.Add("phosphorus");
       
        // Use LambdaExpression to select the  fertilizers that include - "Phosphate"
        var result = fertilizers.Where(inp1 => inp1.Contains("Phosphate"));  
        foreach (var i in result)  
        {  
            Console.WriteLine(i);  
        }  

    }
}

Output:

There are two strings that include “Phosphate” in them.

Explanation:

1. Create a list of string type named “fertilizers”. Add five strings to this list.

2. Here, the expression is used with the “Where” operator. The expression is inp1 => inp1.Contains(“Phosphate”). Then, we use the “foreach” loop to display the strings that are returned by the lambda expression.

Example 3:

Let’s have a list (order_quantity) that holds three orders. Specify the lambda expression to add 5 to each order.

using System;
using System.Linq;
using System.Collections.Generic;

 class LambdaExpressionExample {

    static public void Main()
    {

        // Create List of quantities
        List order_quantity = new List();  
        order_quantity.Add(5);  
        order_quantity.Add(7);  
        order_quantity.Add(8);  
       
        // Use LambdaExpression to 5 to each order.
        var result = order_quantity.Select(inp1 => inp1 + 5);  
        foreach (var i in result)  
        {  
            Console.WriteLine(i);  
        }  

    }
}

Output:

The [5,7,8] list is transformed to [10,12,13].

Explanation:

1. Create the list of quantities of Integer type.

2. We select the orders first and then add 5 to each order. So, the “Select” operator is used. The expression is inp1 => inp1 + 5.

Example 4:

Create a list data source of Event type (with three attributes – Event_Name, Event_Status and Event_Budget) and return the records with the Event_Budget which is greater than 5000.

using System;
using System.Linq;
using System.Collections.Generic;

// Create a class named - 'Event_Source' with 5 events.
public class Event_Source
{
    public static void Main()
    {
        // Event List
        IList events = new List() {
        new Event() {Event_Name = "Technical Camp",Event_Status="Planned",Event_Budget =10000},
        new Event() {Event_Name = "Marketing Camp",Event_Status="Completed",Event_Budget =5000},
        new Event() {Event_Name = "Other",Event_Status="Planned",Event_Budget =1000},
        new Event() {Event_Name = "Politics",Event_Status="Planned",Event_Budget =13000},
        new Event() {Event_Name = "Finance",Event_Status="Completed",Event_Budget =20000},
        };
       
        //Event_Budget greater than 5000.
        var result = events.Where(inp1 => inp1.Event_Budget > 5000);
        foreach(var i in result){          
            Console.WriteLine("NAME: "+i.Event_Name + " STATUS: "+i.Event_Status + " BUDGET: " +i.Event_Budget);
        }
    }
}

public class Event{
    public string Event_Name { get; set; }
    public string Event_Status { get; set; }
    public int Event_Budget { get; set; }
}

Output:

There are three records in the “events” list with the Event_Budget greater than 5000.

Explanation: 

1. First, we create an “Event” class with three attributes.

2. Then, we create a list of five events.

3. Using the inp1 => inp1.Event_Budget > 5000 lambda expression, we select the records with the Event_Budget greater than 5000.

Example 5:

Utilize the previous code and change the lambda expression. Return the events with the Event_Name that ends with “Camp” and with the Event_Status which is “Planned”.

//Lambda Expression - Event_Name ends with "Camp" and Event_Status is "Planned".
        var result = events.Where(inp1 => inp1.Event_Name.EndsWith("Camp") && inp1.Event_Status=="Planned");
        foreach(var i in result){          
            Console.WriteLine("NAME: "+i.Event_Name + " STATUS: "+i.Event_Status + " BUDGET: " +i.Event_Budget);
        }

Output:

There is only one record that satisfies both conditions.

Explanation:

Here, we specify two conditions in the lambda expression. The && (and) operator is used to make the two conditions as True. The first condition uses the EndsWith() method to check if a string ends with the given string. The second condition uses the “Comparison” operator (==) to check if both the values are equal or not.

Conclusion

In C#, the lambda expression takes the expressions/conditional statements as its body without a name. We need to specify the parameters. Then, the expressions are assigned to it. Basically, these are used to filter the records from the given data source, transform the elements, and select the elements from the data source/ sequence. In this guide, we discussed the five different examples that select, filter, and transform the elements using the lambda expression.

Share Button

Source: linuxhint.com

Leave a Reply