Virtual Keyword


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.

Syntax

  • Basic Lambda Expression - (parameters) => expression
  • Example- (x) => x * x

Usage in LINQ

  1. Filtering Data - Using Where method with lambda expressions.
    var adults = employees.Where(e => e.Age >= 18); // Filters employees where Age is 18 or older
  2. Transforming Data - Using Select method with lambda expressions.
    var names = employees.Select(e => e.Name); // Projects only the Name property
  3. Sorting Data - Using OrderBy and ThenBy with lambda expressions.
    var sortedEmployees = employees
        .OrderBy(e => e.Name) // Sorts employees by Name
        .ThenBy(e => e.Age);  // Then sorts by Age

Combining Anonymous Types and Lambda Expressions

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

Prev Next