LINQ (Language Integrated Query) is a powerful feature of C# that provides a way to perform queries over collections, databases, and other data sources. This section will delve into some advanced LINQ techniques in C#.

Key Concepts

  • Deferred Execution: LINQ queries are executed at the point of evaluation, allowing for efficient query execution.
  • Method Syntax vs. Query Syntax: Two ways to write LINQ queries: method syntax (more imperative) and query syntax (more declarative).

Advanced Techniques

  • GroupBy with Key Selector: Grouping elements in a collection based on a specified key.
    var groupedByCategory = books.GroupBy(b => b.Category);
    
  • Custom Operators: Creating custom LINQ operators to extend the functionality.
    public static IEnumerable<TResult> MyCustomOperator<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
    {
        foreach (var item in source)
        {
            yield return selector(item);
        }
    }
    
  • ** deferred Execution Example
    var query = from book in books
                where book.Year > 2010
                select book.Title;
    // The query is not executed here. Execution will happen when the query is enumerated.
    foreach (var title in query)
    {
        Console.WriteLine(title);
    }
    
  • LINQ to XML: Querying XML data using LINQ.
    XDocument doc = XDocument.Load("books.xml");
    var query = from book in doc.Descendants("book")
                where (string)book.Element("price") > "50"
                select book;
    
  • LINQ to SQL: Querying SQL databases using LINQ.
    using (var db = new LibraryContext())
    {
        var query = from book in db.Books
                    where book.Year > 2010
                    select book;
    }
    

Further Reading

For more information on LINQ in C#, consider exploring the following resources:

Advanced LINQ Techniques