System.Linq Namespace
Provides classes and interfaces that support Language Integrated Query (LINQ), which adds native data querying capabilities to .NET languages.
Summary
The System.Linq
namespace is the core of LINQ, offering the fundamental types and operations for querying collections, XML, databases, and other data sources. It introduces extension methods to common collection types, enabling a declarative and expressive way to filter, sort, group, and project data.
Key Concepts
- Query Operators: Methods like
Where
,Select
,OrderBy
,GroupBy
, etc., that transform sequences. - Deferred Execution: Most LINQ queries are not executed until the results are iterated.
- Query Syntax vs. Method Syntax: LINQ can be expressed using a SQL-like query syntax or fluent method calls.
IEnumerable<T>
andIQueryable<T>
: Interfaces representing sequences that LINQ operates on.
Classes
-
Enumerable Class
Contains static methods that query sequences. It is the foundation for LINQ to Objects.
Key Methods:
Where<TSource>(this IEnumerable<TSource>, Func<TSource, bool>)
,Select<TSource, TResult>(this IEnumerable<TSource>, Func<TSource, TResult>)
,OrderBy<TSource, TKey>(this IEnumerable<TSource>, Func<TSource, TKey>)
. -
Queryable Class
Provides extension methods that invoke the query operators that must translate to a
IQueryable
data source.Key Methods: Similar to
Enumerable
but designed forIQueryable<T>
to enable translation to underlying data sources (e.g., SQL).
Interfaces
-
IEnumerable<T> Interface
Represents a sequence of items that can be iterated over. This is the primary interface for LINQ to Objects.
-
IQueryable<T> Interface
Represents a query against a data source.
IQueryable<T>
allows LINQ providers to translate queries into an expression tree that can be executed against various data sources. -
IGrouping<TKey, TElement> Interface
Represents a collection of elements that have a common key.
Example Usage (LINQ to Objects)
Filtering and Projecting
Find all numbers greater than 5 and select their squares.
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var results = numbers
.Where(n => n > 5)
.Select(n => n * n);
foreach (var square in results)
{
Console.WriteLine(square); // Output: 36, 49, 64, 81, 100
}
Grouping
Group words by their length.
var words = new[] { "apple", "banana", "kiwi", "orange", "grape", "pear" };
var groupedByLength = words
.GroupBy(w => w.Length);
foreach (var group in groupedByLength)
{
Console.WriteLine($"Words of length {group.Key}:");
foreach (var word in group)
{
Console.WriteLine($" - {word}");
}
}