Introduction to Language Integrated Query (LINQ)

LINQ (Language-Integrated Query) is a powerful and flexible feature in .NET that enables you to write queries against various data sources directly within your C# or Visual Basic code. It provides a consistent programming model for querying data, regardless of whether the data resides in in-memory collections, databases, XML documents, or other sources.

Why Use LINQ?

Core Concepts

LINQ introduces several fundamental concepts:

LINQ Query Syntax Example (C#)

Let's consider a simple example of querying a list of numbers to find even numbers greater than 5:


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

public class Example
{
    public static void Main(string[] args)
    {
        List numbers = new List { 1, 5, 2, 8, 3, 9, 4, 7, 6 };

        // LINQ Query Syntax
        var evenNumbersGreaterThanFive = from num in numbers
                                         where num > 5 && num % 2 == 0
                                         orderby num
                                         select num;

        Console.WriteLine("Even numbers greater than 5:");
        foreach (var number in evenNumbersGreaterThanFive)
        {
            Console.WriteLine(number);
        }
    }
}
        

LINQ Method Syntax Example (C#)

The same query can be expressed using method syntax:


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

public class Example
{
    public static void Main(string[] args)
    {
        List numbers = new List { 1, 5, 2, 8, 3, 9, 4, 7, 6 };

        // LINQ Method Syntax
        var evenNumbersGreaterThanFive = numbers.Where(num => num > 5 && num % 2 == 0)
                                              .OrderBy(num => num);

        Console.WriteLine("Even numbers greater than 5 (Method Syntax):");
        foreach (var number in evenNumbersGreaterThanFive)
        {
            Console.WriteLine(number);
        }
    }
}
        

LINQ Providers

LINQ can be applied to various data sources through specific LINQ providers:

Key Query Operators

Operator Description
Where Filters elements based on a condition.
Select Projects each element into a new form.
OrderBy / OrderByDescending Sorts elements in ascending or descending order.
GroupBy Groups elements based on a key.
Join Combines elements from two sequences based on matching keys.
Take Returns a specified number of elements.
Skip Bypasses a specified number of elements.
Count Returns the number of elements in a sequence.
Sum / Average / Min / Max Performs aggregate calculations.
Note: LINQ to SQL and LINQ to Entities translate LINQ queries into SQL or Entity SQL respectively, allowing you to interact with relational databases using familiar C# or VB syntax.

Next Steps

Explore the specific LINQ providers to understand how to query different data sources: