Learn About .NET 9 LINQ Enhancements

In the latest .NET 9 preview release, two exciting LINQ methods have been introduced.

CountBy()

  • Counts elements based on specific keys.
  • Simplifies counting tasks by grouping elements and providing counts.

Benefits of .CountBy

  1. Simplicity and Readability
    • The .CountBy  method simplifies the process of grouping elements by a key and counting occurrences.
    • It directly returns a collection of KeyValuePair<TKey, int> where the key represents the group, and the value is the count of elements in that group.
    • This results in cleaner and more intuitive code.
  2. Reduced Complexity
    • Before the introduction of .CountBy, developers had to rely on a combination of .GroupBy and .Select (or .Count) methods.
    • The previous approach involved more code and was less straightforward.

Example

Previous Approach (Before .NET 9)

public class User
 {
     public string? Name { get; set; }
     public string? Role { get; set; }
 }
 internal class Program
 {
     static void Main(string[] args)
     {
        // Define a list of users
         var users = new List<User>
     {
         new User { Name = "Alice", Role = "Admin" },
         new User { Name = "Bob", Role = "Member" },
         new User { Name = "Jay", Role = "Member" },
         new User { Name = "Krishna", Role = "Admin" },
         new User { Name = "An", Role = "Member" },
         new User { Name = "Ka", Role = "Guest" },
         
     };

         // CountBy Role using GroupBy and Select
         var roleCounts = users
             .GroupBy(user => user.Role) // Group users by their roles
             .Select(group => new { Role = group.Key, Count = group.Count() }); // Select the role and count for each group        
      // Print the results
         foreach (var roleCount in roleCounts)
         {
             Console.WriteLine($"Role: {roleCount.Role}, Count: {roleCount.Count}");
         }
     }
 }

Using .CountBy in .NET 9

// With .NET 9, the same operation can be achieved with cleaner code
foreach (var roleCount in users.CountBy(user => user.Role))
{
    Console.WriteLine($"There are {roleCount.Value} users with the role {roleCount.Key}");
}

The output would be

There are 3 users with the role Member
There are 2 users with the role Admin
There is 1 user with the role Guest

AggregateBy
 

Benefits

  • The .AggregateBy method simplifies the process of grouping elements by a key and aggregating values based on that key.
  • It directly returns a collection of KeyValuePair<TKey, TValue> where the key represents the group, and the value is the result of the aggregation operation.

Reduced Complexity

Before the introduction of .AggregateBy, developers had to manually implement custom aggregation logic using loops or multiple LINQ methods.

Previous Approach (Before .NET 9)

// Example: Summing numbers using a loop
var numbers = new List<int> { 1, 2, 3, 4 };
var sum = 0;
foreach (var number in numbers)
{
    sum += number;
}
Console.WriteLine($"Sum: {sum}");

Using .AggregateBy in .NET 9

// Example: Summing numbers using .AggregateBy
var numbers = new List<int> { 1, 2, 3, 4 };
var totalSum = numbers.AggregateBy(n => "Total", (acc, number) => acc + number);
Console.WriteLine($"Total Sum: {totalSum.Value}");

The output would be

Total Sum: 10

In summary, using of .CountBy and .AggregateBy make your code more concise and expressive. It’s a valuable addition to LINQ in .NET 9!

Keep learning!


Similar Articles