What are lambda expressions in LINQ?
Lambda expressions in LINQ are concise and anonymous functions that allow you to write inline, short, and reusable code for data manipulation. These expressions are used to define functions without explicitly specifying a method or a delegate type. Lambda expressions consist of two main elements: parameters and a body.
A lambda expression consists of the following elements:
-
Lambda Operator (=>): It separates the lambda parameters from the lambda body. The lambda operator reads as "goes to" or "becomes."
-
Lambda Parameters: These are the input parameters of the lambda expression. They can be explicitly typed or implicitly inferred by the compiler. Multiple parameters are separated by commas and enclosed in parentheses if there are more than one.
-
Lambda Body: It represents the logic or expression to be executed. It can be a single statement or a block of statements enclosed in curly braces. The body can return a value or perform an action.
Here's a simple example of a lambda expression in LINQ:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Sample list of numbers
List numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Using a lambda expression in LINQ to find even numbers
var evenNumbers = numbers.Where(n => n % 2 == 0);
// Output the even numbers
Console.WriteLine("Even Numbers:");
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
}
}
In this code:
-
We define a list of numbers from 1 to 10.
- We use a lambda expression within the
Where
method of LINQ to filter even numbers from the list.
- The lambda expression
n => n % 2 == 0
has a single parameter n
and a body that checks if n is even (i.e., divisible by 2).
When you run this code, the output will be:
Even Numbers:
2
4
6
8
10
This output demonstrates how a lambda expression is used within a LINQ query to filter and retrieve even numbers from a list. Lambda expressions in LINQ make it easy to write concise and expressive code for data manipulation tasks.