LINQ (Language Integrated Query)
LINQ provides a powerful and flexible way to query data from various sources directly within the C# language. It enables you to write queries that are syntactically similar to SQL but operate on .NET objects, collections, XML, databases, and other data sources.
Core Concepts
LINQ is built around several key concepts:
- Query Syntax: A declarative syntax that resembles SQL, making queries intuitive and readable.
- Method Syntax: An alternative, more fluent syntax using extension methods defined in the
System.Linq.Enumerable
andSystem.Linq.Queryable
classes. - Data Sources: LINQ can query any data source that implements the appropriate interfaces (e.g.,
IEnumerable
,IQueryable
). - Query Operators: A set of standard query operators (e.g.,
Where
,Select
,OrderBy
,GroupBy
) that perform common query operations. - Deferred Execution: Most LINQ queries are not executed until their results are iterated over, allowing for efficient processing and composition.
Query Syntax Example
Example: Filtering and Ordering a List of Numbers
using System;
using System.Collections.Generic;
using System.Linq;
public class LinqQuerySyntax
{
public static void Main(string[] args)
{
List numbers = new List { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
// LINQ Query Syntax
var evenNumbers = from num in numbers
where num % 2 == 0
orderby num descending
select num;
Console.WriteLine("Even numbers in descending order:");
foreach (var number in evenNumbers)
{
Console.Write($"{number} ");
}
// Output: 8 6 4 2 0
}
}
Method Syntax Example
Example: Filtering and Ordering using Method Syntax
using System;
using System.Collections.Generic;
using System.Linq;
public class LinqMethodSyntax
{
public static void Main(string[] args)
{
List words = new List { "apple", "banana", "cherry", "date", "elderberry" };
// LINQ Method Syntax
var shortWords = words.Where(w => w.Length <= 5)
.OrderBy(w => w);
Console.WriteLine("Short words in alphabetical order:");
foreach (var word in shortWords)
{
Console.WriteLine(word);
}
// Output:
// apple
// cherry
// date
}
}
Common Query Operators
LINQ provides a rich set of operators for data manipulation. Here are some of the most common:
Where
Filters a sequence of values based on a predicate.
Select
Projects each element of a sequence into a new form.
OrderBy / OrderByDescending
Sorts the elements of a sequence in ascending or descending order.
GroupBy
Groups the elements of a sequence according to a specified key.
Join
Correlates the elements of two sequences based on matching values.
Distinct
Returns distinct elements from a sequence.
Count
Returns the number of elements in a sequence.
Sum
Calculates the sum of values in a sequence.
Average
Calculates the average of values in a sequence.
First / FirstOrDefault
Returns the first element of a sequence, or a default value.
LINQ to Objects, LINQ to SQL, LINQ to XML
LINQ is a unified programming model that can be used with different data providers:
- LINQ to Objects: Queries collections in memory like arrays, lists, dictionaries, and custom collections.
- LINQ to SQL: Allows querying relational databases (like SQL Server) using LINQ syntax. It translates LINQ queries into SQL statements.
- LINQ to XML: Enables querying XML documents using LINQ syntax, providing a more object-oriented approach than traditional XML DOM manipulation.
Next Steps
Explore the detailed documentation for each query operator, understand how to use LINQ with different data sources, and practice writing your own LINQ queries to enhance your C# development.