CountBy
This is a pretty and very useful method and it is better explained with an example:
Before .NET 9
var roleCounts = users.GroupBy(user => user.Role) // Group users by their roles
.Select(group => new { Role = group.Key, Count = group.Count() });
With .NET 9
var roleCounts = users.CountBy(user => user.Role);
AggregateBy
Use this new method instead of GroupBy to make the syntax clearer:
Before .NET 9
var levelSumByRole = users.GroupBy(user => user.Role)
.Select(group => new { Role = group.Key,
SumByLevel = group.Sum(user => user.Level) });
With .NET 9
var levelSumByRole = users.AggregateBy(
user => user.Role,
seed: 0,
(currentTotal, user) => currentTotal + user.AccessLevel);
Index
More convenient Linq method for getting value and index. Example:
foreach (var (index, item) in people.Index())
{
Console.WriteLine($"Entry {index}: {item}");
}
The same can be achieved before .NET 9 with a more complex syntax:
foreach (var (item, index) in people.Select((item, index) => (item, index)))
{
Console.WriteLine($"Entry {index}: {item}");
}
Note that the item and index are reversed with the Index method.
Top comments (0)