Chapter 8. LINQ Queries
LINQ, or Language Integrated Query, is a set of language and runtime features for writing structured type-safe queries over local object collections and remote data sources.
LINQ enables you to query any collection implementing IEnumerable<T>
, whether an array, list, or XML Document Object Model (DOM), as well as remote data sources, such as tables in an SQL Server database. LINQ offers the benefits of both compile-time type checking and dynamic query composition.
This chapter describes the LINQ architecture and the fundamentals of writing queries. All core types are defined in the System.Linq
and System.Linq.Expressions
namespaces.
Note
The examples in this and the following two chapters are preloaded into an interactive querying tool called LINQPad. You can download LINQPad from http://www.linqpad.net.
Getting Started
The basic units of data in LINQ are sequences and elements. A sequence is any object that implements IEnumerable<T>
, and an element is each item in the sequence. In the following example, names
is a sequence, and "Tom"
, "Dick"
, and "Harry"
are elements:
string[] names = { "Tom", "Dick", "Harry" };
We call this a local sequence because it represents a local collection of objects in memory.
A query operator is a method that transforms a sequence. A typical query operator accepts an input sequence and emits a transformed output sequence. In the Enumerable
class in System.Linq
, there are around 40 query operators—all implemented as static ...
Get C# 12 in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.