Lambda Expressions in LINQ
Lambda expressions are a concise way to represent anonymous methods (functions) in C#. They are used extensively in LINQ queries for specifying conditions, transformations, and other operations.
var adults = employees.Where(e => e.Age >= 18); // Filters employees where Age is 18 or older
var names = employees.Select(e => e.Name); // Projects only the Name property
var sortedEmployees = employees
.OrderBy(e => e.Name) // Sorts employees by Name
.ThenBy(e => e.Age); // Then sorts by Age
You often use anonymous types together with lambda expressions to shape and manipulate data.
Example
var result = employees
.Select(e => new
{
e.Name,
Department = e.Department.ToUpper()
})
.Where(e => e.Department == "IT"); // Project and filter in one query