What's new in .NET 9: Two new LINQ methods

.NET 9 is releasing in mid-November 2024. Like every .NET version, this introduces several important features and enhancements aligning developers with an ever-changing development ecosystem. In this blog series, I will explore critical updates in different areas of .NET. In this post, I'll look at two new LINQ methods: CountBy and AggregateBy.

CountBy

CountBy returns a group-wise count for IEnumerable. Traditionally, if we have to count for each group, we rely on GroupBy and Select (or Count).

Before CountBy:

public class Student
{
    public string Name { get; set; }
    public string Subject { get; set; }
}

// Define a list of students
var students = new List<Student>
{
    new Student { Name = "Martyn", Subject = "Java" },
    new Student { Name = "Cummins", Subject = "C#" },
    new Student { Name = "Jos", Subject = "Java" },
    new Student { Name = "David", Subject = "C#" },
    new Student { Name = "James", Subject = "JavaScript" },
    new Student { Name = "Stuart", Subject = "C#" }
};

// CountBy Subject using GroupBy and Select
var studentCounts = students
    // Group students by their subjects
    .GroupBy(student => student.Subject)
    // Select the role and count for each group
    .Select(group => new { Subject = group.Key, Count = group.Count() });

// Print the results
foreach (var studentCount in studentCounts)
{
    Console.WriteLine($"Subject: {studentCount.Subject}, Count: {studentCount.Count}");
}

The code counts the number of students with each subject by first grouping them by subject and returning an anonymous type with the subject name and the number of students.

With CountBy:

foreach (var studentCount in students.CountBy(student => student.Subject))
{
    Console.WriteLine($"There are {studentCount.Value} students with the role {studentCount.Key}");
}

// Outputs:
// Subject: Java, Count: 2
// Subject: C#, Count: 3
// Subject: JavaScript, Count: 1

Using CountBy simplifies the process by removing the need for a separate GroupBy and Select step. This change not only reduces the lines of code but also enhances readability by making the purpose of the operation more direct.

AggregateBy

AggregateBy performs aggregate operations like Count or Sum for grouped data.

Before AggregateBy:

public class Student
{
    public string Name { get; set; }
    public string Subject { get; set; }
    public double Marks { get; set; }
}

// Define a list of users
var students = new List<Student>
{
    new Student { Name = "Martyn", Subject = "Java", Marks = 7 },
    new Student { Name = "Cummins", Subject = "C#", Marks = 2 },
    new Student { Name = "Jos", Subject = "Java", Marks = 5 },
    new Student { Name = "David", Subject = "C#", Marks = 4 },
    new Student { Name = "James", Subject = "JavaScript" , Marks = 2},
    new Student { Name = "Stuart", Subject = "C#", Marks = 1 }
};

var marksBySubject = students
    .GroupBy(student => student.Subject) 
    .Select(group => new { Subject = group.Key, TotalMarks = group.Sum(student => student.Marks) }); 

// Print the results
foreach (var mark in marksBySubject)
{
    Console.WriteLine($"Total Marks for subject {mark.Subject} is {mark.TotalMarks}");
}

The code calculates the total marks for each subject by grouping students based on their subject and returning an anonymous type with the subject name and the cumulative marks of students in that subject.

With AggregateBy:

var marksBySubject = students
    .AggregateBy(
        student => student.Subject,
        seed: 0,
        (currentTotal, student) => currentTotal + student.Marks);

// Print the results
foreach (var markAggregate in marksBySubject)
{
    Console.WriteLine($"Total Marks for subject {markAggregate.Key} is {markAggregate.Value}");
}

// Outputs:
// Total Marks for subject Java is 12
// Total Marks for subject C# is 7
// Total Marks for subject JavaScript is 2

AggregateBy reduces the need for multiple calls to GroupBy and aggregation functions, such as Sum, by letting us perform all the operations directly in one line. This approach enhances performance by eliminating intermediate collections, improving maintainability, and making the logic clearer.

Conclusion

.NET is releasing in November 2024 with lots of enhancements and additions. In this post, I reviewed two significant updates to LINQ in the form of the CountBy and AggregateBy methods. They are compact methods for complex operations which are traditionally performed with manual and multiple steps. The inclusion of these methods eliminates those intermediate steps. Code maintainability, readability, and performance are improved. What's not to like 😄