LINQ is a set of features introduced in .NET Framework 3.5 that allows us to perform functional compositions that work on iterables.
LINQ queries can be written in two interchangeable ways:
- Query expression syntax (query syntax)
- Method syntax (method syntax).
Both syntaxes are functionally equivalent, and the choice between them depends on developer preference and the context of use.
LINQ is one of the wonders of C#. It is very, very powerful. You should get used to using it as soon as you can because it’s a gem.
LINQ Syntax
LINQ can be used in two main ways in C#: with query syntax and with method syntax.
Method Syntax
Method syntax uses extension methods and lambdas to create queries.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = numbers.Where(number => number % 2 == 0);
Query Syntax
Query syntax resembles SQL and is more intuitive for those familiar with SQL queries.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = from number in numbers
where number % 2 == 0
select number;
Common Operations in LINQ
Filtering
Filtering is done using the Where method.
var evenNumbers = numbers.Where(number => number % 2 == 0);
Projection
Projection transforms data into a new form. The Select method is used for this purpose.
var squares = numbers.Select(number => number * number);
Sorting
Sorting is achieved with the OrderBy and OrderByDescending methods.
var sortedAsc = numbers.OrderBy(number => number);
var sortedDesc = numbers.OrderByDescending(number => number);
Grouping
Grouping is performed with the GroupBy method.
var grouped = numbers.GroupBy(number => number % 2 == 0 ? "Evens" : "Odds");
Aggregation
Aggregation summarizes the values of a collection using methods like Count, Sum, Average, Min, and Max.
int sum = numbers.Sum();
int count = numbers.Count();
double average = numbers.Average();
int min = numbers.Min();
int max = numbers.Max();
LINQ to Objects
LINQ to Objects allows querying in-memory collections like arrays and lists. This is the most common and basic way to use LINQ.
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry", "Peach" };
var fruitsWithA = from fruit in fruits
where fruit.Contains("a")
select fruit;
foreach (var fruit in fruitsWithA)
{
Console.WriteLine(fruit);
}
LINQ to XML
LINQ to XML allows querying and manipulating XML documents easily.
XDocument xmlDoc = XDocument.Load("fruits.xml");
var fruitsWithA = from fruit in xmlDoc.Descendants("fruit")
where fruit.Value.Contains("a")
select fruit;
foreach (var fruit in fruitsWithA)
{
Console.WriteLine(fruit.Value);
}
LINQ to SQL
LINQ to SQL allows interacting with SQL Server databases using LINQ syntax.
DataContext db = new DataContext("connectionString");
var customers = from customer in db.GetTable<Customer>()
where customer.City == "Madrid"
select customer;
foreach (var customer in customers)
{
Console.WriteLine(customer.Name);
}
