Advertisement
Intermediate C# Lesson 7 of 8

Lesson 7: LINQ with XML and IQueryable

LINQ to XML provides a powerful way to query and transform XML documents using familiar LINQ patterns. This lesson also explains when to use IEnumerable versus IQueryable.

Advertisement

Querying XML with XDocument

LINQ to XML uses XDocument and XElement to parse XML into a queryable tree.

using System.Xml.Linq;

var xml = XDocument.Parse(@"
  LINQ in Action2020
  Modern C#2023
");

var titles = xml.Descendants("book")
    .Select(book => book.Element("title")?.Value)
    .Where(title => title != null);

Selecting XML Values

Use Element and Value to extract content from XML nodes.

var recentBooks = xml.Descendants("book")
    .Where(book => int.Parse(book.Element("year")?.Value ?? "0") >= 2021)
    .Select(book => new
    {
        Title = book.Element("title")?.Value,
        Year = int.Parse(book.Element("year")?.Value ?? "0")
    });

IEnumerable vs IQueryable

IEnumerable<T> executes queries in memory. IQueryable<T> can translate queries to external providers (like databases) before execution.

TypeWhen to Use
IEnumerable<T>In-memory collections, immediate local iteration.
IQueryable<T>Remote data sources, deferred translation to SQL or XML providers.

Provider Translation Example

When LINQ uses IQueryable, the expression tree can be converted into a provider-specific query, such as SQL or XML navigation.

🧠 Quick Check — Lesson 7

Which type is usually used for database query translation?

Lesson Summary

LINQ to XML lets you query XML documents with the same LINQ operators you use for collections.

XDocument and XElement are the core LINQ to XML building blocks.

IEnumerable is for in-memory iteration; IQueryable is for provider-backed translation.

Use IQueryable when you want LINQ expressions to become SQL or provider-specific queries.