Menu

Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Monday, 16 December 2024

.NET 9 Index in LINQ

 

About


Index is one of feature introduced in .NET LINQ. By using this method, we can easily extract implicit index of IEnumerable.

The other .NET 9 LINQ features are as follows.

The Index method returns index and index of an item in following format.

Format: IEnumerable<(int Index, TSource Item)>

Scenario


Lets consider to display employee name in list and their respective order.

Employee class


public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}


Setup Employee List with Sample Data

var employees = new List {
  new Employee(){ Id = 11, Name = "Ram" },
  new Employee(){ Id = 12, Name = "Bheem" },
  new Employee(){Id = 13, Name = "Lakshman"},
  new Employee(){Id = 14, Name = "Hanu"},
  new Employee(){Id = 15, Name = "Dev"},
  new Employee(){Id = 16, Name = "Nandan"},
  new Employee(){Id = 17, Name = "Krish"},
  new Employee(){Id = 18, Name = "Hash"},
};

  foreach ((int index, Employee emp) in employees.Index())
  {
      Console.WriteLine($"Index: {index}, Employee Name: {emp.Name}");
  }
  
Screenshots

The following code and output screenshots gives easy understanding and for your implementation.

Code



Output



Summary



This post explored about Index feature in LINQ introduced in .NET9.
Thanks for reading this and stay tuned for more articles.

Sunday, 15 December 2024

.NET 9 AggregateBy LINQ

 About


In this post, we are exploring about AggregateBy LINQ method introduced in .NET 9. This is very helpful and being used in scenarios of aggregate operations such as sum, average and grouping of data based on custom conditions.

In Earlier post, Please look into about other feature discussed about CountBy in LINQ 9. 

So, Lets go ahead to discuss/understand about AggregateBy in LINQ.

Scenario


Lets consider following scenario and understand implementation of this before and after .NET 9 approach.

"Get sum of employee merit score points based on job level"

Employee class

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int YearJoin { get; set; }
    public int JobLevel { get; set; }
    public int MeritPoints { get; set; }
}

Setup Employee List with Sample Data

  var employees = new List {
  new Employee(){ Id = 11, Name = "Ram", YearJoin = 2015, JobLevel = 6, MeritPoints = 10 },
  new Employee(){ Id = 12, Name = "Bheem", YearJoin = 2012, JobLevel = 5, MeritPoints = 20 },
  new Employee(){Id = 13, Name = "Lakshman", YearJoin = 2015, JobLevel = 6, MeritPoints = 30},
  new Employee(){Id = 14, Name = "Hanu", YearJoin = 2016, JobLevel = 6, MeritPoints = 40},
  new Employee(){Id = 15, Name = "Dev", YearJoin = 2024, JobLevel = 6, MeritPoints = 50},
  new Employee(){Id = 16, Name = "Nandan", YearJoin = 2012, JobLevel = 5, MeritPoints = 60},
  new Employee(){Id = 17, Name = "Krish", YearJoin = 2012, JobLevel = 5, MeritPoints = 70},
  new Employee(){Id = 18, Name = "Hash", YearJoin = 2015, JobLevel = 6, MeritPoints = 80},
};

Before .NET 9

//BEFORE .NET 9 Example
// Aggregate MeritPoints by Job Level using GroupBy and Aggregate
var meritPointsByEmpJobLevel = employees
    .GroupBy(user => user.JobLevel) // Group users by their Job Level
    .Select(group => new
    {
        JobLevel = group.Key,
        TotalMeritPoints = group.Sum(user => user.MeritPoints)
    }
            ); // Aggregate Merit Points for each Job Level
// Print the results
foreach (var jobLevelAggregate in meritPointsByEmpJobLevel)
{
    Console.WriteLine($"Total merit points per each employee level " +
        $"{jobLevelAggregate.JobLevel} is {jobLevelAggregate.TotalMeritPoints}");
}

Aforesaid code example, we did the following steps.
1. Group the employees based on Job level.
2. Select the Job level as Key and Sum of Meri points on respective job level.
3. Display the results in fore ach loop based on select results.

.NET 9

var totalEmpMeritPointsByLevel = employees.AggregateBy(e => e.JobLevel, 
                                    seed: 0, (acc, meritPoints) => acc + meritPoints.MeritPoints);
foreach (var meritPointByLevel in totalEmpMeritPointsByLevel)
{
    Console.WriteLine($"Total merit points per each employee level " +
        $"{meritPointByLevel.Key} is {meritPointByLevel.Value}");
}

The aforesaid .NET 9 code example, we achieved all in one go with AggregateBy example. The code also very clean and crsip.

Syntax:

IEnumerable<(TKey Key, TAccumulate Aggregate)> AggregateBy(
    this IEnumerable source,
    Func keySelector,
    Func seedFactory,
    Func aggregator
);

Screenshots

Code



Output


Summary


In this post, we explored about AggregateBy LINQ feature with ease of use and code examples. Those are really helpful to improve developer productivity and ease of understanding and performance of applications.
Thanks for reading and Stay tuned for more articles!!


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.