Menu

Tuesday, 10 December 2024

.NET 9 CountBy LINQ


Introduction

.NET 9 is the latest version of Microsoft's released in Nov 2024. Its open-source development platform for building applications for web, mobile, desktop and cloud environments. 

This release is pack of many new features, LINQ methods and performance improvements and many more.

About

In this post, we are focusing about one of new LINQ method introduced in .NET 9. Its very useful, comprehensive and easily can understand and can be used in our project as well :).

So, Lets start explore on this.

Scenario

Lets consider a easy scenario as "To get employees count based on the year joined".

Employee Class:

public class Employee

{

    public int Id { get; set; }

    public string Name { get; set; }

    public int YearJoin { get; set; }

}

Setup Employee List with Sample Data

  var employees = new List<Employee> {

  new Employee(){ Id = 11, Name = "Ram", YearJoin = 2015 },

  new Employee(){ Id = 12, Name = "Bheem", YearJoin = 2012 },

  new Employee(){ Id = 13, Name = "Lakshman", YearJoin = 2015 },

  new Employee(){ Id = 14, Name = "Hanu", YearJoin = 2016 },

  new Employee(){ Id = 15, Name = "Dev", YearJoin = 2024 },

  new Employee(){ Id = 16, Name = "Nandan", YearJoin = 2012 },

  new Employee(){ Id = 17, Name = "Krish", YearJoin = 2012 },

  new Employee(){ Id = 18, Name = "Hash", YearJoin = 2015 },

};

So, First let us understand - How we are doing currently (Earlier to .NET 9).

Before .NET 9

Approach is - Grouping and Counting

1. GroupBy: Groups the employees based on their value provided (Year).

2. Select(g => new {Key = g.Key, Value = g.Count()}}: project each group into anonymous object with two properties.

  • Key: The year joined.
  • Value: The count of occurrences of employees in the group.
Sample Code:

var empOccurences = employees

                .GroupBy(c => c.YearJoin)
                .Select(g => new { g.Key, Value = g.Count() });

foreach (var empInfo in empOccurences)
{
    Console.WriteLine($"There are {empInfo.Value} users with the year joined {empInfo.Key}");
}

.NET 9

In .NET 9 -Its simplifies the process and streamlined code like below.

foreach (var empCount in employees.CountBy(user => user.YearJoin))
{
    Console.WriteLine($"There are {empInfo.Value} users with the year joined {empInfo.Key}");
}

Screenshots
Code



Output



CountBy Benefits

  • Simplifies the code hence it improves readability and developer productivity.
  • Optimizes the performance by streamlining the grouping and counting process.
  • It makes data aggregation makes more efficient and concise. 

I will come up with another LINQ method introduced in .NET 9 in upcoming post. Stay tuned!!

Thanks for your reading and provide your comments and suggestions as always.

No comments:

Post a Comment