</>
CompilerOnline
Open Interactive Editor

C# LINQ (Language Integrated Query)

Language Integrated Query (LINQ)

LINQ is the name for a set of technologies based on the integration of query capabilities directly into the C# language. It allows querying collections, databases, and XML in a declarative format.

Syntax Flavors:

  • Query Syntax (resembles SQL query syntax).
  • Method Syntax (uses lambda expressions and extension methods).

A key feature of LINQ is deferred execution: queries are not executed when defined, but rather when the query variable is iterated over in a loop or converted to a list.

LINQ queries return strongly-typed collections, allowing the C# compiler to check for syntax and type errors at compile-time, preventing runtime database errors.

LINQ Method Syntax

LINQ Method Syntax utilizes extension methods and lambda parameters (such as nums.Select() and nums.Sum()) to aggregate collection objects concisely.

csharp
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
    static void Main() {
        List<int> nums = new List<int> { 1, 2, 3, 4 };
        int doubleSum = nums.Select(x => x * 2).Sum();
        Console.WriteLine("Double Sum: " + doubleSum);
    }
}
csharp
using System;
using System.Linq;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] scores = { 97, 60, 82, 100, 50 };
        var highScores = scores.Where(s => s >= 80).OrderByDescending(s => s);
        foreach (var score in highScores) {
            Console.WriteLine(score);
        }
    }
}