LINQ (Language Integrated Query)

LINQ is a powerful set of technologies in .NET that adds native data querying capabilities to .NET languages. It allows you to write queries against collections of objects, XML documents, databases, and other data sources in a consistent, C#-like syntax.

Key Concepts

  • Query Syntax: A declarative syntax similar to SQL for writing queries.
  • Method Syntax: Using extension methods from the System.Linq.Enumerable and System.Linq.Queryable classes.
  • Deferred Execution: Queries are not executed until the results are actually needed.
  • Standard Query Operators: A rich set of methods for filtering, projecting, ordering, grouping, and joining data.

LINQ Providers

LINQ can be extended to query various data sources through different LINQ providers:

  • LINQ to Objects: For querying in-memory collections like arrays and lists.
  • LINQ to SQL: For querying SQL Server databases.
  • LINQ to XML: For querying and manipulating XML documents.
  • Entity Framework: A more advanced Object-Relational Mapper (ORM) that supports LINQ queries against relational databases.

Example: LINQ to Objects

Here's a simple example of querying a list of numbers:

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

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

        // Query syntax
        var evenNumbersQuery = from num in numbers
                               where num % 2 == 0
                               orderby num
                               select num;

        Console.WriteLine("Even numbers (Query Syntax):");
        foreach (var number in evenNumbersQuery)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine();

        // Method syntax
        var oddNumbersMethod = numbers.Where(num => num % 2 != 0).OrderByDescending(num => num);

        Console.WriteLine("Odd numbers (Method Syntax):");
        foreach (var number in oddNumbersMethod)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine();
    }
}
                    
                

Further Reading