When developing applications with .NET, we often need to retrieve, filter, sort, and transform data from collections or databases.
But how can we perform these operations in a clean and readable way?
This is where LINQ (Language Integrated Query) comes in.
LINQ is a powerful feature in C# that allows developers to query data directly within their code. It makes working with collections easier and helps us write more readable and maintainable applications.
Let's explore five commonly used LINQ methods with practical examples.
Getting Started
First, let's create a simple product list that we will use throughout this article.
var products = new List<Product>
{
new Product { Name = "Laptop", Price = 25000, Category = "Electronics" },
new Product { Name = "Mouse", Price = 500, Category = "Electronics" },
new Product { Name = "Keyboard", Price = 1500, Category = "Electronics" },
new Product { Name = "Chair", Price = 4000, Category = "Furniture" },
new Product { Name = "Desk", Price = 6000, Category = "Furniture" }
};
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
Now, let's see how LINQ can help us work with this data.
1. Where() – Filtering Data
The Where() method allows us to filter a collection based on a specific condition.
For example, let's find all products with a price greater than 1,000.
var result = products
.Where(p => p.Price > 1000)
.ToList();
foreach (var product in result)
{
Console.WriteLine(product.Name);
}
Output:
Laptop
Keyboard
Chair
Desk
The Where() method returns all elements that match the given condition.
2. Select() – Transforming Data
Sometimes, we don't need all the properties of an object. We may only want to retrieve specific information.
For example, let's get only the product names.
var result = products
.Select(p => p.Name)
.ToList();
foreach (var name in result)
{
Console.WriteLine(name);
}
Output:
Laptop
Mouse
Keyboard
Chair
Desk
The Select() method is useful when we want to transform data into a different format or retrieve only specific properties.
3. OrderBy() – Sorting Data
What if we want to sort products by price, from lowest to highest?
We can use the OrderBy() method.
var result = products
.OrderBy(p => p.Price)
.ToList();
foreach (var product in result)
{
Console.WriteLine($"{product.Name} - {product.Price}");
}
Output:
Mouse - 500
Keyboard - 1500
Chair - 4000
Desk - 6000
Laptop - 25000
If we want to sort the products in descending order, we can use OrderByDescending() instead.
4. FirstOrDefault() – Finding the First Matching Element
Sometimes, we only need the first element that matches a specific condition.
For example, let's find the first product with a price greater than 5,000.
var result = products
.FirstOrDefault(p => p.Price > 5000);
Console.WriteLine(result?.Name ?? "Product not found");
Output:
Laptop
An important detail: FirstOrDefault() returns the default value if no matching element is found. For reference types, this is usually null.
5. GroupBy() – Grouping Data
The GroupBy() method allows us to organize data based on a shared property.
For example, let's group products by their category.
var result = products
.GroupBy(p => p.Category);
foreach (var group in result)
{
Console.WriteLine(group.Key);
foreach (var product in group)
{
Console.WriteLine($"- {product.Name}");
}
}
Output:
Electronics
- Laptop
- Mouse
- Keyboard
Furniture
- Chair
- Desk
GroupBy() is particularly useful when working with reports, statistics, and category-based data.
Bonus: Combining Multiple LINQ Methods
One of the best features of LINQ is that we can combine multiple methods in a single query.
For example, let's find products in the Electronics category and sort them by price in descending order.
var result = products
.Where(p => p.Category == "Electronics")
.OrderByDescending(p => p.Price)
.Select(p => p.Name)
.ToList();
foreach (var name in result)
{
Console.WriteLine(name);
}
Output:
Laptop
Keyboard
Mouse
With a single query, we filtered, sorted, and transformed the data.
Conclusion
LINQ is an essential feature for C# developers. It provides a clean and readable way to work with data without writing complex loops for every operation.
Here is a quick summary:
Where()– Filters data based on a condition.Select()– Transforms data or selects specific properties.OrderBy()– Sorts data in ascending order.FirstOrDefault()– Returns the first matching element or a default value.GroupBy()– Groups elements based on a shared property.
Understanding these methods will make everyday C# development easier and help you write cleaner code.
Remember: LINQ queries can work with different data sources. For example, LINQ to Objects works with in-memory collections, while Entity Framework Core can translate LINQ queries into SQL and execute them against a database.
The key is knowing which LINQ operations to use and understanding where your query is executed.
Comments
Please log in to leave a comment.
No comments yet. Be the first!