New LINQ methods in C# 13: Index, CountBy, AggregateBy

profile
Tim Deschryver
timdeschryver.dev

In this article, we will explore the new LINQ methods that (normally) will be introduced in C# 13, as part of the .NET 9 release during .NET Conf 2024. These new methods are Index, CountBy, and AggregateBy.

Warning

These LINQ methods are part of the release candidate, the final release may include changes or removals.

Note

Upgrading to .NET 9 will give you a ton of LINQ optimizations, which you automatically get for free!

The examples throughout this article use the following data collection. We have a collection of 5 students, each with a name and a score.

Index link

The Index() method (Enumerable.Index) adds an index to each element in the collection. The index is a 0-based integer that represents the position of the element in the collection.

The example below simply adds an index to each student in the collection.

Output:

CountBy link

The CountBy() method (Enumerable.CountBy<TSource, TKey>) groups the elements in the collection by a key and returns the count of elements in each group.

The example below groups the students by their score and counts the number of students in each group.

Output:

It's also possible to use add an expression to build the identifier for the group. The example below groups the students by their score ("A" or "B" means the student has passed) and counts the number of students that passed or failed.

Output:

CountBy() can also accept a comparer (IEqualityComparer<TKey>? keyComparer) as the second argument.

AggregateBy link

The AggregateBy() method (Enumerable.AggregateBy<TSource, TKey, TAccumulate>) groups the elements in the collection by a key and aggregates (similar to Aggregate()) the elements in each group.

The first argument is the key selector, creating the group. The second argument is the initial value (seed) for each group. The third argument is the function that aggregates the elements in the group, it receives the value of the group and the current element.

The example below groups students by their scores.

Output:

AggregateBy() can also accept a comparer (IEqualityComparer<TKey>? keyComparer) as the last argument.

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post