Language INtegrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.

LINQ is a .NET-based DSL (Domain Specific Language) for querying data sources such as databases, XML files, or in-memory object lists. All these data sources can be queried using the exact same readable and easy-to-use syntax - or rather, syntaxes, because LINQ supports two notations:

Inline LINQ or query syntax, where queries are expressed in a SQL-like language, with dialects in both C# and VB.NET.

Fluent LINQ or query operators, where queries are expressed as lambda expressions and can be linked (LINQed?) using a fluent syntax. This is also called method chaining.

Some examples:

Query syntax (C#)

var result = 
    from product in dbContext.Products
    where product.Category.Name == "Toys"
    where product.Price >= 2.50
    select product.Name;

Query Syntax (VB.NET)

Dim result = _
    From product in dbContext.Products _
    Where product.Category.Name = "Toys" _
    Where product.Price >= 2.50 _
    Select product.Name

Fluent syntax

var result = dbContext.Products
    .Where(p => p.Category.Name == "Toys" && p.Price >= 250)
    .Select(p => p.Name);

This query would return the name of all products in the "Toys" category with a price greater than or equal to 2.50.

Flavors

LINQ comes in many flavors, the most notable are

  • LINQ to Objects - For querying collections of POCO (Plain Old CLR Objects)
  • LINQ to SQL - For querying SQL databases
  • LINQ to Entities - For querying SQL databases through Entity Framework
  • LINQ to XML - For querying XML documents

There are other implementations of LINQ which can be found on the Internet, such as LINQ to SharePoint, LINQ to Twitter, LINQ to CSV, LINQ to Excel, LINQ to JSON, and LINQ to Google.

More reading:

history | excerpt history