New LINQ Methods

The CountBy Method

The CountBy method allows you to group items and returns an IEnumerable of Key-Value Pairs.

For example, in the code below there is a method that has a string (sourceText), and there is a LINQ query that does the following:

  • Split: it splits the string into an array of words using space, period and comma as delimiters.
  • Select: it converts each word to lowercase
  • CountyBy: this is the new LINQ method, which groups the item (in this example, a word) in a key-value pair.
  • MaxBy: it finds the most frequent word in the string.

The output is:

amet

The AggregateBy Method

The AggregateBy method allows you to group items and calculate values that are associated with a given key.

For demonstration purposes, I created the ScoreEntry class that will be used in the next example. This class has a PlayerId property of type string and a Score property of type int:

In the code below we group the items (in this example, the ScoreEntry items), and it sums the value Score associated with a given key (PlayerId):

The AggregateBy method receives three parameters:

  • The first parameter is the item we want to group, which in this case is the PlayerId.
  • The second parameter is the seed, which means the increment we want to apply. In this case, it is zero, if we add 1, it will sum the value 1 in the total.
  • The third parameter is the tuple, which sums the score for each element.

The output is:

[1, 90]
[2, 50]
[3, 10]

The Index Method

The Index method allows you to extract the index of an Enumerable.

For demonstration purposes, I created a User class, which contains a Name property of type string, that is going to be used for this example:

Using the Index method, we can return the index and the related value for each item, for example:

The Index method returns a sequence of tuples where each tuple contains an index and the corresponding value from the users collection. The tuple is deconstructed into two variables: index and user. This allows simultaneous access to both the index and the user object for each item in the collection.

The output is:

Index 0 - Ana
Index 1 - Camille
Index 2 - Bob
Index 3 - Jasmine

In the previous .NET version, we could do the same thing but with Select:

foreach (var (user, index) in users.Select((user, index) => (user, index)))
Console.WriteLine($"Index {index} - {user.Name}");

But now with the Index method, it’s simpler and easier to achieve the same result.

Conclusion

These new LINQ methods are coming in .NET 9, and provide an easy way to group items and return index positions of items in a list. Note that this is still in a preview version, so there might be some changes until the official release date in November 2024.

Share this post