LINQ Methods in .NET 9 and C# 13 : Index, CountBy, and AggregateBy

In this article, I will explore the new LINQ methods Index, CountBy, and AggregateBy introduced in .NET 9. These powerful features are designed to enhance LINQ’s functionality and flexibility, making it even more valuable for developers. By using these methods, you can simplify complex data tasks, write cleaner and more efficient code, and improve your overall development experience.

.NET 9 LINQ Enhancements

.Net 9 : New Linq methods

Let’s dive into each method with in-depth explanations and practical code examples. We will explore how Index, CountBy, and AggregateBy can improve your coding experience and simplify data manipulation tasks in .NET 9.

Create a Console Application using the .NET 9 Framework.

Linq new methods

Note. Let’s go through each method one by one, in detail, with code snippets and examples.

Index

  • The Index<T> method in LINQ, introduced with .NET 9, offers a way to traverse a collection while simultaneously obtaining the index and value of each element. This is particularly beneficial when both the position and value of an element are required during iteration, a task that was less intuitive before this method became available.
Syntax
IEnumerable<(int Index, T Value)> Index<T>(this IEnumerable<T> source);

How does the index method Work?

For each element in the collection, the Index method produces a tuple that includes:

  • The Index of the element in the sequence.
  •  The value of the element itself.

Let’s take an example of an employee class with a primary constructor:

public class Employee(int id, string name, string department)
{
    public int Id { get; set; } = id;
    public string Name { get; set; } = name;
    public string Department { get; set; } = department;
}
// Creating a list of employees
List<Employee> employees =
        [
            new Employee(1, "Jignesh Kumar", "HR"),
            new Employee(2, "Chintan patel", "IT"),
            new Employee(3, "Emily Johnson", "Marketing")
        ];

// Using the Index method to get both index and employee data
var _indexedEmployees = employees.Index();

foreach (var (index, employee) in _indexedEmployees)
{
    Console.WriteLine($"Index: {index}, Employee: {employee.Name}, Department: {employee.Department}");
}
dot net 9 LINQ new method Index
Real-Time Debugging Using Visual Studio

Output

Index: 0, Employee: Jignesh Kumar, Department: HR
Index: 1, Employee: Chintan patel, Department: IT
Index: 2, Employee: Emily Johnson, Department: Marketing

Key Benefits of Index()

  • Tuple return type: The method provides a tuple containing both the index and value, enabling straightforward access to both during iteration.
  • Simplifies logic: This feature simplifies use cases where the element’s position is required, eliminating the need to manually track an index variable.

Before the introduction of the Index method in .NET 9.

Using Select with Index

LINQ’s Select method has an overload that includes an index parameter. Developers often used this to retrieve the index and value of each element in a collection.

How did developers achieve similar functionality before the Index method in .NET 9?

List<Employee> employees =
           [
              new Employee(1, "Jignesh Kumar", "HR",50000),
              new Employee(2, "Chintan Patel", "IT",30000),
              new Employee(3, "Emily Johnson", "Marketing",20000)
           ];

var indexedEmployees = employees
    .Select((employee, index) => new { Index = index, employee = employee })
    .ToList();

foreach (var item in indexedEmployees)
{
    Console.WriteLine($"Index: {item.Index}, Name: {item.employee.Name}");
}

CountBy

The CountBy method introduced in .NET 9 is a LINQ extension that streamlines the process of grouping elements by a key and counting the occurrences within each group. By replacing the more complex combination of GroupBy and Select methods, it offers a cleaner, more intuitive approach to writing such queries.

Syntax

IEnumerable<(TKey Key, int Count)> CountBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector
);

How does the CountBy method work?

The method returns an IEnumerable of tuples, where each tuple contains:

  • Key: The key of the group.
  • Count: The number of elements in that group.

Let’s add more data to the employee list so we can use the CountBy method effectively on the expanded dataset.

List<Employee> employees =
        [
            new Employee(1, "Jignesh Kumar", "HR"),
            new Employee(2, "Chintan Patel", "IT"),
            new Employee(3, "Emily Johnson", "Marketing"),
            new Employee(3, "Kyle James", "IT"),
            new Employee(3, "Peter Moor", "Marketing"),
            new Employee(3, "Make Patel", "IT"),
        ];

// Apply the CountBy method to the employee list

var departmentCounts = employees.CountBy(emp => emp.Department);

// Loop through and retrieve the count for each department

foreach (var (department, count) in departmentCounts)
{
    Console.WriteLine($"Department: {department}, Employee Count: {count}");
}
CountBy .Net 9 Linq Method
CountBy : Real-Time Debugging Using Visual Studio
Output
Department: HR, Employee Count: 1
Department: IT, Employee Count: 3
Department: Marketing, Employee Count: 2

Before the introduction of the CountBy method in .NET 9.

Using GroupBy and Select

To count elements grouped by a specific key (e.g., department in an employee list), you needed to:

  1. Group the elements using GroupBy.
  2. Count the elements in each group using Select.

How did developers achieve similar functionality before the CountBy method in .NET 9?

var departmentCounts = employees
    .GroupBy(emp => emp.Department) // Group employees by department
    .Select(group => new
    {
        Department = group.Key,
        Count = group.Count() // Count employees in each group
    })
    .ToList();

// Output the counts
foreach (var item in departmentCounts)
{
    Console.WriteLine($"Department: {item.Department}, Count: {item.Count}");
}

AggregateBy

The AggregateBy method in .NET 9 is a robust LINQ extension designed to streamline aggregate operations such as summing, averaging, or applying custom calculations on grouped data. It offers a more concise and expressive alternative to using a combination of GroupBy with Select or implementing manual aggregation logic.

Syntax

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

How does AggregateBy Work?

  1. Groups the elements based on the key provided by the keySelector.
  2. It uses the seed factory to initialize an accumulator for each group.
  3. Applies the aggregator function to calculate the aggregate value for each group.
List<Employee> employees =
            [
                new Employee(1, "Jignesh Kumar", "HR",50000),
                 new Employee(2, "Chintan Patel", "IT",30000),
                 new Employee(3, "Emily Johnson", "Marketing",20000),
                 new Employee(3, "Kyle James", "IT", 50000),
                 new Employee(3, "Peter Moor", "Marketing", 30000),
                 new Employee(3, "Make Patel", "IT",45000),
            ];

// Apply the CountBy method to the employee list

var departmentSalaries = employees.AggregateBy(
            emp => emp.Department,                    // Group by Department
            0m,                                // Seed: Start with 0 salary (initialize as decimal)
            (totalSalary, employee) => totalSalary + employee.Salary  // Aggregate: Sum salaries
        ).ToList();

// Loop through and retrieve the count for each department
// Output the results
foreach (var (department, totalSalary) in departmentSalaries)
{
    Console.WriteLine($"Department: {department}, Total Salary: {totalSalary:C}");
}
AggregateBy method in Dot Net 9
AggregateBy : Real-Time Debugging Using Visual Studio
Output
Department: HR, Total Salary:  50,000.00
Department: IT, Total Salary:  1,25,000.00
Department: Marketing, Total Salary:  50,000.00

Before the introduction of the AggregateBy method in .NET 9.

Using GroupBy and Select

To aggregate data for each group, you would:

  1. Use GroupBy to group elements by a specific key.
  2. Use Select to project each group into a key-value pair where the value is computed using an aggregate function.

How did developers achieve similar functionality before the AggregateBy method in .NET 9?

var departmentSalaries = employees
    .GroupBy(emp => emp.Department)
    .Select(group => new
    {
        Department = group.Key,
        TotalSalary = group.Sum(emp => emp.Salary)
    })
    .ToList();


foreach (var item in departmentSalaries)
{
    Console.WriteLine($"Department: {item.Department}, Total Salary: {item.TotalSalary}");
}

Summary

In this article, I have demonstrated the power and utility of the new LINQ methods introduced in .NET 9 Index, CountBy, and AggregateBy and how they simplify code while improving readability. I provided examples of how developers handled similar tasks before these methods and highlighted the benefits of the new LINQ features in .NET 9.

Thank you for reading! I hope it was helpful. Please feel free to leave a comment and reach out if you have any questions.

What is Scrum ? How to Implement Scrum Methodology in Agile Project Management

In this article, I will elucidate the Scrum process within Agile project management. I’ll delve into the roles integral to Scrum methodology. This article will provide a comprehensive overview of the Scrum process within agile development. I will explain the core components of Scrum, exploring the end-to-end Scrum process in detail. By the end of this article, you’ll gain a clear understanding of how Scrum works and its impact on achieving successful agile outcomes.

What is scrum?

Scrum is an Agile framework for managing complex projects, mainly software development. Scrum's iterative process is built around Sprints, timeboxed intervals typically consist of 1-4 weeks that allow teams to deliver working software increments in a short time.
Scrum process
Scrum Framework

Scrum process in agile product development

  1. Roles Involved: Product Owner, Scrum Master, and Development Team within the Scrum Framework.
  2. Terminology used: defining key Scrum terms such as sprint, backlog, velocity, burndown chart, etc.
  3. Events: Sprint Planning, Daily Scrums, Sprint Review, and Sprint Retrospective.
  4. Artifacts: analyzing the essential artifacts used in Scrum, such as the product backlog, sprint backlog, and increment.

What is a scrum team?

A Scrum team is a small team that has mainly three roles product owner, scrum master, and development team, which is a cross-functional group of individuals who work together to deliver product increments. The Scrum Team is self-organizing and cross-functional that works collaboratively to achieve the Sprint Goal and deliver valuable increments of the product.

Scrum Team : Scrum master, product owner, stakeholders and development team
Scrum Team

What are the main roles in the Scrum team?

The main roles in a scrum team are,

  • Product Owner: He/She is responsible for prioritizing the product backlog and maximizing the product’s value, Setting the Sprint Goal, Providing Clarifications and Acceptance Criteria, and Participating in Sprint Events. The Product Owner ensures that the scrum team delivers a high-quality product that meets customer expectations and achieves business goals.
  • Scrum Master: The Scrum Master is important in facilitating the Scrum process and ensuring the team adheres to its principles and practices. Facilitates the scrum process, removes impediments, promotes self-organization in the team, ensuring transparency, protecting the team, and continuous improvement in agile development
  • Development Team: The development team plays a vital role in Scrum, working together to deliver valuable product increments that meet customer expectations and contribute to the overall success of the project.Cross-functional and self-organized professionals who will work collaboratively to deliver valuable product increments at the end of each Sprint.

What are the scrum events in the scrum process?

A scrum set of events which is also known as scrum ceremonies, to facilitate communication, collaboration, and transparency within the Scrum Team and with stakeholders. There are mainly four main events Sprint Planning, Daily Stand-up (Daily Scrum), Sprint Review, Sprint Retrospective

1. Sprint Planning

  • Sprint planning is the first event of the scrum sprint. All team members collectively define the sprint scope, It’s a collaborative effort where the team decides what they’ll achieve in the upcoming sprint and how many user stories can be taken based on estimation done and according to team capacity. In this event team picks a subset of Product Backlog items that can be completed within the sprint timeline.
  • The team assesses their capacity for the sprint, considering factors like team size, available resources, technical challenges, and potential dependencies.
Sprint Planning Meeting

Daily Stand-up (Daily Scrum)

  • Daily stand-up is one of the crucial events for any successful scrum team. This event keeps scrum teams on track. It’s a short, time-framed meeting (typically 15 minutes) where the development team updates on progress and identifies any roadblocks.
  • Daily Scrum Format: Each member answers three questions
    1. What did I do yesterday?
    2. What will I do today?
    3. Are there any impediments preventing me from progressing further?
Daily Standup meeting
Daily Stand-Up

Sprint Review

Sprint Review
Sprint Review Meeting

Sprint Retrospective

A Sprint retrospective is the last event of each scrum sprint, It’s a time for the team to look back at the sprint just finished, identify what worked well, and what could be improved, and make action items for future sprints.

The Sprint Retrospective is an open and honest discussion, encouraging all team members to contribute their perspectives and give their valuable opinions on the just completed sprint.

Sprint Retrospective
7. Sprint Retrospective

What are the artifacts of scrum?

Product Backlog

  • The product backlog is a core element of the scrum framework. It contains the list of prioritized items that need to be done to improve the product. It includes features, bug fixes, and technical debt that the team needs to deliver to reach the desired product outcome.
  • Core Components of the Product Backlog.
    • Epics: Large size of work that can be broken down into smaller, manageable pieces.
    • User Stories: A user story is a fundamental unit of work in the product backlog within the Scrum framework. It represents a single piece of functionality or feature from the perspective of the end user.
    • Features: Larger pieces of functionality that provide significant value for the end user.
    • Bugs: Issues that need to be fixed to improve the product’s functionality or performance(the product’s quality).
    • Tasks: Specific pieces of work derived from user stories.
    • Technical Debt: Refactoring and improvements needed in the codebase to improve code quality.
Product Backlog
8. Product Backlog

Sprint Backlog

The sprint backlog is a key artifact in the Scrum framework. The Sprint Backlog in Scrum is a list of tasks or user stories selected from the Product Backlog for completion during a sprint. It is a subset of the product backlog and it is created during the sprint planning meeting.

Sprint backlog
9. Sprint Backlog

Increment

At the conclusion of each sprint iteration, the Increment should represent a usable outcome derived from the current sprint and align with the predefined Definition of Done criteria. Below, I’ve included a snippet to illustrate the visualization of the increment within the Scrum process.

Product Increment
10. Increment

Core terminology used in Scrum.

  1. Sprint: A sprint cycle typically lasts 1 to 4 weeks and involves a series of scheduled meetings and events. It begins with sprint planning, includes daily stand-ups and review meetings, and concludes with a retrospective.
  2. Product Backlog: The product backlog includes features, functionalities, technical debt, improvements, bug fixes, user stories, non-functional requirements, and research and development tasks required for product improvement.
  3. Sprint Backlog: Selected items that the team needs to complete development during a specific sprint. It includes user stories prioritized by the product owner to deliver in the current sprint.
  4. Sprint Planning: A meeting where the team selects and plans the work for the upcoming sprint. User stories are chosen from the product backlog based on priority, and the team then breaks these stories down into smaller, actionable tasks for the current sprint.
  5. Daily Scrum: A daily scrum is a short meeting (typically 15 minutes) where the team syncs on the progress of the team. During the daily scrum meeting, each team member provides updates on three key points: what they accomplished yesterday, what they plan to do today, and if they’re facing any impediments in their progress.
  6. Sprint Review: A meeting where the team showcases the completed increment to the stakeholder or product owner and gathers feedback from them.
  7. Sprint Retrospective: This meeting is the last event of each scrum sprint. It’s a time for the team to look back at the sprint just finished, identify what worked well, what did not go well, and what could be improved, and make action items for future sprints.
  8. Burndown Chart: A visual representation of the remaining work in the sprint backlog over time. The chart shows whether the team is on track to complete all planned work by the end of the sprint. It helps to identify what needs to be done and how much time is left in the current sprint to complete planned work.
  9. Velocity: Velocity is calculated by summing up the story points of all the user stories completed in a sprint. It is a measure of the team’s productivity, indicating how much work they can accomplish in a sprint.
  10. Scrum board: A scrum board that helps scrum teams manage their work. Usually, sticky notes are used to show the current status of a task by moving from one status to another, like “To do”, “In progress”, and “done”.

Summary

In this article, I have explained how the Scrum process functions within agile project management. I covered the Scrum process in detail, including the roles involved, the key artifacts, and the events that occur during a Scrum sprint. Additionally, I provided examples and visual representations to help readers better understand the Scrum framework in agile development.

I hope you find this helpful! Happy reading !!!