LINQ (Language Integrated Query)

LINQ provides a powerful and flexible way to query data from various sources directly within the C# language. It enables you to write queries that are syntactically similar to SQL but operate on .NET objects, collections, XML, databases, and other data sources.

Core Concepts

LINQ is built around several key concepts:

Query Syntax Example

Example: Filtering and Ordering a List of Numbers


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

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

        // LINQ Query Syntax
        var evenNumbers = from num in numbers
                          where num % 2 == 0
                          orderby num descending
                          select num;

        Console.WriteLine("Even numbers in descending order:");
        foreach (var number in evenNumbers)
        {
            Console.Write($"{number} ");
        }
        // Output: 8 6 4 2 0
    }
}
                

Method Syntax Example

Example: Filtering and Ordering using Method Syntax


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

public class LinqMethodSyntax
{
    public static void Main(string[] args)
    {
        List words = new List { "apple", "banana", "cherry", "date", "elderberry" };

        // LINQ Method Syntax
        var shortWords = words.Where(w => w.Length <= 5)
                              .OrderBy(w => w);

        Console.WriteLine("Short words in alphabetical order:");
        foreach (var word in shortWords)
        {
            Console.WriteLine(word);
        }
        // Output:
        // apple
        // cherry
        // date
    }
}
                

Common Query Operators

LINQ provides a rich set of operators for data manipulation. Here are some of the most common:

LINQ to Objects, LINQ to SQL, LINQ to XML

LINQ is a unified programming model that can be used with different data providers:

Next Steps

Explore the detailed documentation for each query operator, understand how to use LINQ with different data sources, and practice writing your own LINQ queries to enhance your C# development.