.NET9 Alpha - LINQ updates
In the latest .NET 9 Alpha release, LINQ (Language Integrated Query) introduces powerful new methods such as CountBy
and AggregateBy
, enhancing the simplicity and readability of data manipulation. These methods provide a more intuitive approach to common tasks like counting and aggregating elements based on specific keys, reducing complexity.
CountBy
Before the introduction of the CountBy
method in LINQ, we had to rely on a combination of the GroupBy
and Select
(or Count
) methods to group elements by a key and then count the occurrences of each group.
Before .NET 9
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Define a list of users
var users = new List<User>
{
new User { Name = "Alice", Role = "Admin" },
new User { Name = "Bob", Role = "Member" },
new User { Name = "Charlie", Role = "Admin" },
new User { Name = "David", Role = "Member" },
new User { Name = "Eve", Role = "Guest" },
new User { Name = "Frank", Role = "Admin" }
};
// CountBy Role using GroupBy and Select
var roleCounts = users
.GroupBy(user => user.Role) // Group users by their roles
.Select(group => new { Role = group.Key, Count = group.Count() }); // Select the role and count for each group
// Print the results
foreach (var roleCount in roleCounts)
{
Console.WriteLine($"Role: {roleCount.Role}, Count: {roleCount.Count}");
}
}
}
// User class definition
public class User
{
public string Name { get; set; }
public string Role { get; set; }
// Add more properties if needed
}
While this method is flexible, it requires a bit more code.
With .NET 9
With the introduction of CountBy
in .NET 9, the same operation can be achieved with much cleaner and more intuitive code. CountBy
simplifies the process by internally handling the grouping and counting, directly returning a collection of KeyValuePairs
where the key is the group and the value is the count of elements in that group.
foreach (var roleCount in users.CountBy(user => user.Role))
{
Console.WriteLine($"There are {roleCount.Value} users with the role {roleCount.Key}");
}
Output would be:
There are 3 users with the role Admin
There are 2 users with the role Member
There are 1 users with the role Guest
AggregateBy
We’ll introduce a new property to the User
class, say AccessLevel
, which is an integer. We'll then aggregate these access levels by user role.
Before .NET 9
Before AggregateBy
, you would typically use GroupBy
along with Aggregate
to accomplish this task.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Define a list of users
var users = new List<User>
{
new User { Name = "Alice", Role = "Admin", AccessLevel = 10 },
new User { Name = "Bob", Role = "Member", AccessLevel = 5 },
new User { Name = "Charlie", Role = "Admin", AccessLevel = 20 },
new User { Name = "David", Role = "Member", AccessLevel = 5 },
new User { Name = "Eve", Role = "Guest", AccessLevel = 1 },
new User { Name = "Frank", Role = "Admin", AccessLevel = 10 }
};
// Aggregate AccessLevel by Role using GroupBy and Aggregate
var accessLevelSumByRole = users
.GroupBy(user => user.Role) // Group users by their roles
.Select(group => new { Role = group.Key, TotalAccessLevel = group.Sum(user => user.AccessLevel) }); // Aggregate AccessLevel for each role
// Print the results
foreach (var roleAggregate in accessLevelSumByRole)
{
Console.WriteLine($"Total AccessLevel for role {roleAggregate.Role} is {roleAggregate.TotalAccessLevel}");
}
}
}
// User class definition
public class User
{
public string Name { get; set; }
public string Role { get; set; }
public int AccessLevel { get; set; }
}
With .NET 9
With the introduction of AggregateBy
, you can perform the same operation more succinctly.
// AggregateBy AccessLevel using AggregateBy
var accessLevelSumByRole = users.AggregateBy(
user => user.Role,
seed: 0,
(currentTotal, user) => currentTotal + user.AccessLevel);
// Print the results
foreach (var roleAggregate in accessLevelSumByRole)
{
Console.WriteLine($"Total AccessLevel for role {roleAggregate.Key} is {roleAggregate.Value}");
}
Output would be:
Total AccessLevel for role Admin is 40
Total AccessLevel for role Member is 10
Total AccessLevel for role Guest is 1
While LINQ methods like
CountBy
andAggregateBy
have been available through third-party libraries such asSuperLinq
, offering a rich set of extended functionalities for LINQ, the official inclusion of these methods in the .NET 9 Alpha release marks a significant milestone. It signifies Microsoft's commitment to enhancing the LINQ library itself, integrating these powerful and much-requested features directly into the core framework ensuring robust support and optimization directly from the primary maintainers of the .NET ecosystem Microsoft + Open Source & Microsoft Design
Refer to the proposal tickets:
I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!
📚 For more insights like these, feel free to follow 👉 Merwan Chinta