C# LINQ Tutorial: Query Collections Easily
LINQ, or Language Integrated Query, provides a powerful way to work with collections in C#. It allows developers to filter, sort, transform, group, and search data using concise and readable code.
What is LINQ in C#?
LINQ is a set of features in C# that allows queries to be written directly in the language. It works with arrays, lists, collections, databases, XML, and other data sources.
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
Why Use LINQ?
- Write shorter and cleaner collection queries
- Filter data easily
- Sort and group collections
- Transform objects into new data
- Improve readability of collection-processing code
Using Where
The Where method filters a collection based on a condition.
var ages = new List<int> { 15, 18, 21, 25, 30 };
var adults = ages.Where(age => age >= 18);
Using Select
The Select method transforms each item in a collection into another value or object.
var names = new List<string> { "Alice", "Bob", "Charlie" };
var lengths = names.Select(name => name.Length);
Sorting with OrderBy
OrderBy sorts elements in ascending order, while OrderByDescending sorts them in descending order.
var numbers = new List<int> { 40, 10, 30, 20 };
var ascending = numbers.OrderBy(n => n);
var descending = numbers.OrderByDescending(n => n);
Using First and FirstOrDefault
First returns the first matching element, while FirstOrDefault returns the default value when no matching element exists.
var numbers = new List<int> { 10, 20, 30 };
var first = numbers.First();
var result = numbers.FirstOrDefault(n => n > 100);
Using Any and All
Any checks whether at least one element satisfies a condition. All checks whether every element satisfies a condition.
bool hasLargeNumber = numbers.Any(n => n > 25);
bool allPositive = numbers.All(n => n > 0);
Using GroupBy
GroupBy organizes elements into groups based on a selected key.
var students = new[]
{
new { Name = "Alice", Grade = "A" },
new { Name = "Bob", Grade = "B" },
new { Name = "John", Grade = "A" }
};
var grouped = students.GroupBy(s => s.Grade);
LINQ Method Table
| Method | Purpose | Example |
|---|---|---|
| Where | Filter elements | Where(x => x > 10) |
| Select | Transform elements | Select(x => x.Name) |
| OrderBy | Sort ascending | OrderBy(x => x.Name) |
| GroupBy | Create groups | GroupBy(x => x.Category) |
| First | Get first element | First() |
| Any | Check for matching elements | Any(x => x > 10) |
| Count | Count elements | Count() |
Combining LINQ Methods
LINQ methods can be chained together to build more complex queries while keeping the code readable.
var result = students
.Where(s => s.Grade == "A")
.Select(s => s.Name)
.OrderBy(name => name);
LINQ Query Syntax
C# also supports query syntax, which provides an SQL-like way to express LINQ queries.
var result = from student in students
where student.Grade == "A"
select student.Name;
Deferred Execution
Many LINQ queries use deferred execution, meaning the query is evaluated when its results are actually enumerated rather than immediately when the query is created.
var query = numbers.Where(n => n > 10);
foreach (var number in query)
{
Console.WriteLine(number);
}
Real-World Applications
- Filtering products in e-commerce applications
- Searching users in web applications
- Sorting records in dashboards
- Grouping sales data
- Transforming database query results
Common Mistakes to Avoid
- Creating unnecessarily complex LINQ chains
- Ignoring deferred execution
- Calling ToList repeatedly without need
- Using LINQ when a simple loop is clearer
- Loading large datasets unnecessarily
Advanced LINQ Concepts
- IEnumerable and IQueryable
- Deferred execution
- Projection
- Joins
- Aggregation
- Expression trees
- LINQ with Entity Framework
Practice Exercises
- Filter a list of numbers
- Find products above a specific price
- Sort a list of users by name
- Group employees by department
- Find the highest value using Max
- Calculate an average using Average
Conclusion
LINQ makes collection processing in C# more expressive and convenient. By learning methods such as Where, Select, OrderBy, GroupBy, Any, and First, developers can write clean and maintainable data-processing code.