System.Linq Namespace
Overview
LINQ allows you to write queries against collections of objects, XML documents, databases, and other data sources in a uniform way. It offers a declarative syntax that makes queries more readable and concise compared to traditional loop-based data manipulation.
LINQ Providers
LINQ itself is a specification. The actual execution of queries depends on the LINQ provider that understands how to translate LINQ queries into operations on a specific data source. Common LINQ providers include:
- LINQ to Objects: For querying in-memory collections like arrays and lists.
- LINQ to SQL: For querying relational databases using SQL Server.
- LINQ to XML: For querying XML documents.
- Entity Framework: A more modern ORM that supports LINQ queries against relational databases.
LINQ Query Syntax
Query syntax is a set of keywords that resemble SQL query structure, making it intuitive for developers familiar with database querying.
LINQ Method Syntax
Method syntax uses extension methods defined on the IEnumerable<T>
and IQueryable<T>
interfaces. It's often used when query syntax is not sufficient or for chaining operations.
Key LINQ Extension Methods
Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Filters a sequence of values based on a predicate.
Parameters:
source
: AnIEnumerable<T>
to filter.predicate
: A function to test each element of the sequence for a condition.
Example:
Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
Projects each element of a sequence into a new form.
Parameters:
source
: AnIEnumerable<T>
to project.selector
: A transform function to apply to each element.
Example:
OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
Sorts the elements of a sequence in ascending order.
Parameters:
source
: AnIEnumerable<T>
whose elements to sort.keySelector
: A function to extract a key from each element.
Example:
GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
Groups the elements of a sequence according to a specified key selector function.
Parameters:
source
: AnIEnumerable<T>
whose elements to group.keySelector
: A function to extract the keys that group elements.
Example:
ToList<TSource>(this IEnumerable<TSource> source)
Converts an IEnumerable<T>
to a List<T>
.
Example:
FirstOrDefault<TSource>(this IEnumerable<TSource> source)
Returns the first element of a sequence, or a default value if the sequence contains no elements.
Example:
This documentation provides a high-level overview of LINQ within the System.Linq
namespace. For detailed API specifications and advanced topics, please refer to the official Microsoft documentation.