SortBy, FilterBy, and CombineBy in NET 9
By FoxLearn 2/22/2025 3:43:16 AM 5
.NET 9 introduces several new LINQ methods to streamline common data manipulation tasks. These methods aim to make code more readable and reduce the complexity of achieving common goals.
SortBy
The SortBy method in LINQ, introduced in .NET 9, allows you to easily sort elements in a collection based on a provided key. It simplifies sorting by key and reduces the need for complex LINQ queries.
Syntax:
IEnumerable<T> SortBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector);
The SortBy method sorts elements in a collection based on a key extracted from each element.
For example, sort a list of products based on price
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public Product(int id, string name, decimal price) { Id = id; Name = name; Price = price; } } List<Product> products = new List<Product> { new Product(1, "Laptop", 1200.99m), new Product(2, "Smartphone", 800.49m), new Product(3, "Tablet", 300.79m) }; // Sorting by Price using the SortBy method var sortedProducts = products.SortBy(p => p.Price); foreach (var product in sortedProducts) { Console.WriteLine($"Product: {product.Name}, Price: {product.Price:C}"); }
Output:
Product: Tablet, Price: $300.79 Product: Smartphone, Price: $800.49 Product: Laptop, Price: $1,200.99
Key Benefits of SortBy:
- Simplified sorting: No need to manually use
OrderBy
. - Cleaner code: Directly integrates sorting into your LINQ queries.
Before .NET 9, developers would often use OrderBy
to sort a collection:
var sortedProducts = products.OrderBy(p => p.Price).ToList();
FilterBy
The FilterBy method is another enhancement in .NET 9 that simplifies the process of filtering elements based on a given condition. It replaces more verbose filtering methods and makes the code easier to read.
Syntax:
IEnumerable<T> FilterBy<T>(this IEnumerable<T> source, Func<T, bool> predicate);
The FilterBy method filters the collection by applying a predicate function to each element. It returns only those elements that satisfy the condition.
For example, filter employees by department
public class Employee { public int Id { get; set; } public string Name { get; set; } public string Department { get; set; } public Employee(int id, string name, string department) { Id = id; Name = name; Department = department; } } List<Employee> employees = new List<Employee> { new Employee(1, "John Doe", "HR"), new Employee(2, "Jane Smith", "IT"), new Employee(3, "Sam Brown", "HR") }; // Filtering by Department using FilterBy method var hrEmployees = employees.FilterBy(e => e.Department == "HR"); foreach (var employee in hrEmployees) { Console.WriteLine($"Employee: {employee.Name}, Department: {employee.Department}"); }
Output:
Employee: John Doe, Department: HR Employee: Sam Brown, Department: HR
Key Benefits of FilterBy:
- Streamlined filtering: Directly applies a condition without needing
Where
. - Improved readability: The name
FilterBy
makes the intent of the code clearer.
Before .NET 9, developers would filter collections like this:
var hrEmployees = employees.Where(e => e.Department == "HR").ToList();
CombineBy
The CombineBy method in .NET 9 is designed to combine elements based on a key and apply an operation to aggregate the results. This method makes grouping and aggregation tasks easier by providing a clear, concise syntax.
Syntax:
IEnumerable<T> CombineBy<T, TKey, TAccumulate>(this IEnumerable<T> source, Func<T, TKey> keySelector, Func<TAccumulate> seedFactory, Func<TAccumulate, T, TAccumulate> aggregator);
The CombineBy method groups elements by a key and then applies an aggregation function to each group.
For example, Combine employees' total salary by department
List<Employee> employees = new List<Employee> { new Employee(1, "John Doe", "HR", 50000), new Employee(2, "Jane Smith", "IT", 60000), new Employee(3, "Sam Brown", "HR", 55000) }; // Combining by Department and calculating total salary var departmentSalaries = employees.CombineBy( e => e.Department, // Group by Department 0, // Initial salary: 0 (total, emp) => total + emp.Salary // Aggregator: Sum of salaries ); foreach (var department in departmentSalaries) { Console.WriteLine($"Department: {department.Key}, Total Salary: {department.Value:C}"); }
Output:
Department: HR, Total Salary: $105,000.00 Department: IT, Total Salary: $60,000.00
Key Benefits of CombineBy:
- Improved aggregation: Directly integrates grouping and aggregation logic.
- Flexible: Allows any aggregation operation to be applied.
Before .NET 9, a similar result would require GroupBy
followed by a Select
with an aggregation function:
var departmentSalaries = employees .GroupBy(e => e.Department) .Select(group => new { Department = group.Key, TotalSalary = group.Sum(e => e.Salary) }).ToList();
In this article, we've explored the new LINQ methods SortBy, FilterBy, and CombineBy introduced in .NET 9. These enhancements simplify common tasks like sorting, filtering, and aggregating data, improving both the clarity and efficiency of code. By using these methods, you can dramatically reduce code complexity while enhancing the readability of your LINQ queries in .NET 9.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
- Connection string password with special characters in C#