LINQ, short for Language Integrated Query, is a powerful feature in C# that simplifies data querying and manipulation. It provides a consistent syntax for working with various data sources, including arrays, collections, XML, and databases.
LINQ integrates query capabilities directly into C#, allowing developers to write expressive and readable queries using a SQL-like syntax. It bridges the gap between object-oriented programming and data manipulation, making it easier to work with different data structures.
LINQ queries typically follow this structure:
var result = from item in dataSource
where condition
select item;
Alternatively, you can use method syntax:
var result = dataSource.Where(item => condition)
.Select(item => item);
Let's look at a practical example using LINQ to filter and sort a list of numbers:
List<int> numbers = new List<int> { 5, 10, 15, 20, 25, 30 };
var result = from num in numbers
where num > 15
orderby num descending
select num;
foreach (var num in result)
{
Console.WriteLine(num);
}
// Output:
// 30
// 25
// 20
LINQ shines when working with complex objects. Here's an example using a custom class:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 20 }
};
var youngPeople = people.Where(p => p.Age < 28)
.OrderBy(p => p.Name);
foreach (var person in youngPeople)
{
Console.WriteLine($"{person.Name} - {person.Age}");
}
// Output:
// Alice - 25
// Charlie - 20
LINQ can work with various data sources through different providers:
LINQ is a cornerstone of modern C# development, offering a unified approach to data manipulation. By mastering LINQ, developers can write more efficient and expressive code, streamlining data operations across various platforms and data sources.