New LINQ Methods in .NET 9 Preview

Introduction

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.

Note that as these methods are still in a Preview version, some changes might happen 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); 
       
       //O/P : 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:

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);
	
	// Output:
	// [1, 90]
	// [2, 50]
	// [3, 10]
}

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

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

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

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}");

	// Output:
	// Index 0 - Ana
	// Index 1 - Camille
	// Index 2 - Bob
	// Index 3 - Jasmine
}

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

	public User(string name)
	{
		Name = 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.

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.