← Back to Curriculum

LINQ (Language Integrated Query)

📚 Lesson 9 of 15 ⏱ 50 min

LINQ (Language Integrated Query)

50 min

LINQ provides a unified way to query data from different sources (collections, databases, XML), enabling consistent query syntax across data types. LINQ integrates query capabilities directly into C#, making queries first-class language features. LINQ queries are type-safe and checked at compile time. Understanding LINQ enables powerful data manipulation. LINQ is one of C#'s most distinctive features.

LINQ methods include Where (filtering), Select (projection), OrderBy (sorting), GroupBy (grouping), and Aggregate (aggregation), providing comprehensive data manipulation capabilities. Method syntax uses extension methods on IEnumerable<T>. Query syntax uses SQL-like keywords. Both syntaxes compile to the same code. Understanding LINQ methods enables effective data queries. LINQ methods are composable and chainable.

LINQ can work with collections (in-memory data), databases (Entity Framework), and XML (LINQ to XML), providing a consistent query experience. LINQ to Objects queries in-memory collections. LINQ to SQL/Entity Framework queries databases. LINQ to XML queries XML documents. Understanding LINQ providers enables querying diverse data sources. LINQ's provider model enables extensibility.

Query syntax and method syntax are both supported, giving you flexibility in how you write queries. Query syntax (from...where...select) is more readable for complex queries. Method syntax (Where().Select()) is more flexible and composable. Both compile to the same code. Understanding both syntaxes enables choosing the best approach. Method syntax is more commonly used.

LINQ uses deferred execution—queries aren't executed until enumerated, enabling efficient query composition. Deferred execution allows building complex queries without immediate execution. ToList(), ToArray(), or enumeration triggers execution. Understanding deferred execution enables efficient queries. Deferred execution is a key LINQ feature.

Best practices include using LINQ for data queries, understanding deferred execution, using method syntax for composability, avoiding multiple enumerations, and using appropriate LINQ methods. Understanding LINQ enables powerful, readable data manipulation. LINQ is essential for modern C# development.

Key Concepts

  • LINQ provides unified query syntax for different data sources.
  • LINQ methods: Where, Select, OrderBy, GroupBy, Aggregate.
  • LINQ works with collections, databases, and XML.
  • Query syntax and method syntax are both supported.
  • LINQ uses deferred execution—queries execute when enumerated.

Learning Objectives

Master

  • Writing LINQ queries with method and query syntax
  • Using common LINQ methods (Where, Select, OrderBy, GroupBy)
  • Understanding deferred execution
  • Querying different data sources with LINQ

Develop

  • Understanding functional programming concepts
  • Designing efficient data queries
  • Appreciating LINQ's role in C#

Tips

  • Use method syntax for composability and flexibility.
  • Understand deferred execution—queries execute when enumerated.
  • Use Select() for projection, Where() for filtering.
  • Chain LINQ methods for complex queries.

Common Pitfalls

  • Not understanding deferred execution, causing multiple enumerations.
  • Using LINQ for simple operations that don't need it.
  • Not using appropriate LINQ methods, writing inefficient queries.
  • Mixing query and method syntax unnecessarily.

Summary

  • LINQ provides unified query syntax for different data sources.
  • LINQ methods enable powerful data manipulation.
  • LINQ works with collections, databases, and XML.
  • Understanding LINQ enables powerful data queries.
  • LINQ is essential for modern C# development.

Exercise

Demonstrate LINQ operations with different data sources.

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

class Program
{
    static void Main(string[] args)
    {
        // Sample data
        var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var names = new List<string> { "Alice", "Bob", "Charlie", "David", "Eve" };
        
        // Method syntax
        var evenNumbers = numbers.Where(n => n % 2 == 0);
        Console.WriteLine("Even numbers:");
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
        
        // Query syntax
        var longNames = from name in names
                       where name.Length > 4
                       select name.ToUpper();
        
        Console.WriteLine("\nLong names (uppercase):");
        foreach (var name in longNames)
        {
            Console.WriteLine(name);
        }
        
        // Complex LINQ operations
        var result = numbers
            .Where(n => n > 5)
            .Select(n => n * 2)
            .OrderByDescending(n => n);
        
        Console.WriteLine("\nNumbers > 5, doubled, descending:");
        foreach (var num in result)
        {
            Console.WriteLine(num);
        }
        
        // Aggregation
        var sum = numbers.Sum();
        var average = numbers.Average();
        var max = numbers.Max();
        
        Console.WriteLine($"\nSum: {sum}, Average: {average}, Max: {max}");
    }
}

Code Editor

Output