DEV Community

.Net Trends
.Net Trends

Posted on

New LINQ methods coming in .NET 9

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() });
Enter fullscreen mode Exit fullscreen mode

With .NET 9


var roleCounts = users.CountBy(user => user.Role);
Enter fullscreen mode Exit fullscreen mode

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) });
Enter fullscreen mode Exit fullscreen mode

With .NET 9

var levelSumByRole = users.AggregateBy(
    user => user.Role,
    seed: 0,
    (currentTotal, user) => currentTotal + user.AccessLevel);
Enter fullscreen mode Exit fullscreen mode

Index
More convenient Linq method for getting value and index. Example:

foreach (var (index, item) in people.Index())
{
    Console.WriteLine($"Entry {index}: {item}");
}

Enter fullscreen mode Exit fullscreen mode

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}");
}
Enter fullscreen mode Exit fullscreen mode

Note that the item and index are reversed with the Index method.

More: https://dotnetrends.net/new-linq-methods.html

Top comments (0)