.NET March 20, 2024
5 min read

.NET 9 Preview — New LINQ Methods

While the release of .NET 9 is planned for November 2024, the preview version is already available. One of the new .NET 9 features is the new LINQ methods: CountBy, AggregateBy and Index. In this article, I present how to use these methods.

For demonstration purposes, I created a console application using .NET version 9.0.100-preview.2.24157.14. The complete code can be found on my GitHub.

Note that as these methods are still in a Preview version, it might happen some changes until the official release.

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.
public static class CountyByDemo
{
   public static void Execute()
   {
	   string sourceText = """
		   Lorem ipsum dolor sit amet, consectetur adipiscing elit.
		   Sed non risus. Suspendisse lectus tortor, dignissim sit amet, 
		   adipiscing nec, ultricies sed, dolor. Cras elementum ultrices amet diam.
	   """;

	   KeyValuePair<string, int> mostFrequentWord = sourceText
		   .Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries)
		   .Select(word => word.ToLowerInvariant())
		   .CountBy(word => word)
		   .MaxBy(pair => pair.Value);

	   Console.WriteLine(mostFrequentWord.Key);
   }
}

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:

private class ScoreEntry
{
   public string PlayerId { get; init; }
   public int Score { get; init; }

   public ScoreEntry(string playerId, int score)
   {
	   PlayerId = playerId;
	   Score = score;
   }
}

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):

public static class AggregateByDemo
{
	public static void Execute()
	{
		var scoreEntries = new List<ScoreEntry>
		{
			new ("1", 50),
			new ("2", 20),
			new ("1", 40),
			new ("3", 10),
			new ("2", 30)
		};

		 var aggregatedData = scoreEntries
			 .AggregateBy(
				 keySelector: entry => entry.PlayerId,
				 seed: 0,
				 (totalScore, curr) => totalScore + curr.Score
			 );
  
		foreach (var item in aggregatedData)
			Console.WriteLine(item);
	}
}

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:

private class User
{
   public string Name { get; init; }

   public User(string name)
   {
	   Name = name;
   }
}

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

public static class IndexDemo
{
   public static void Execute()
   {
	   var users = new List<User>
	   {
		   new ("Ana"),
		   new ("Camille"),
		   new ("Bob"),
		   new ("Jasmine")
	   };

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

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

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.

This is the link for the project in GitHub: https://github.com/henriquesd/DotNet9NewLinqMethods

If you like this demo, I kindly ask you to give a ⭐️ in the repository.

Thanks for reading!


References

What’s new in .NET 9 — Microsoft Docs