🔥 Pragmatic .NET Code Rules Course is on Presale - 40% off!BUY NOW

.NET 9 - New LINQ Methods

Sponsored

• Tired of outdated API documentation holding your team back? Postman simplifies your life by automatically syncing documentation with your API updates - no more static docs, no more guesswork! Read more.

Many thanks to the sponsors who make it possible for this newsletter to be free for readers. Become a sponsor.

The background

.NET 9 introduces exciting enhancements to LINQ (Language Integrated Query), adding new methods - Index, CountBy, and AggregateBy. These methods streamline data manipulation and improve performance in scenarios involving counting, aggregation, and accessing indices. Let’s dive into these additions, understand their practical applications, and see them in action.

1. CountBy: Simplified Grouped Counting

The CountBy method simplifies counting occurrences of elements based on a key. Unlike GroupBy, it directly produces a dictionary-like result of counts by key, reducing code complexity and intermediate allocations.

Example: Let’s count the occurrences of first names in a list of people.

C#
var people = new List<Person>{ new Person("Steve", "Jobs"), new Person("Steve", "Carell"), new Person("Elon", "Musk")}; var countByFirstName = people.CountBy(p => p.FirstName); foreach (var entry in countByFirstName){ Console.WriteLine($"There are {entry.Value} people with the name {entry.Key}");} // Output:// There are 2 people with the name Steve// There are 1 people with the name Elon

Why It’s Useful:

  1. Eliminates the need for GroupBy followed by Select.
  2. Reduces code verbosity and increases clarity.

2. AggregateBy: Key-Based Aggregations Made Easy

AggregateBy allows you to aggregate values by a key, all in a single operation. It combines the functionality of GroupBy and Aggregate into a single, optimized step.

Example: Aggregate salaries by job title to compute the total salary for each role.

C#
var employees = new List<Employee>{ new Employee("Alice", "Developer", 70000), new Employee("Bob", "Developer", 80000), new Employee("Charlie", "Manager", 90000), new Employee("Dave", "Manager", 95000)}; var salaryByRole = employees.AggregateBy( emp => emp.Role, seed: 0, (totalSalary, emp) => totalSalary + emp.Salary); foreach (var entry in salaryByRole){ Console.WriteLine($"Total salary for {entry.Key}: {entry.Value}");} // Output:// Total salary for Developer: 150000// Total salary for Manager: 185000

Why It’s Useful:

  1. Reduces intermediate groupings and simplifies aggregation logic.
  2. Offers performance benefits in scenarios with large datasets.

3. Index: Access Elements with Indices

The Index method returns elements along with their indices, making it easier to iterate through collections when you need both the element and its position. Example: Iterate over a list of people, displaying their index and name.

C#
var people = new List<Person>{ new Person("Steve", "Jobs"), new Person("Steve", "Carell"), new Person("Elon", "Musk")}; foreach ((var index, var person) in people.Index()){ Console.WriteLine($"Entry {index}: {person.FirstName} {person.LastName}");} // Output:// Entry 0: Steve Jobs// Entry 1: Steve Carell// Entry 2: Elon Musk

Why It’s Useful:

  1. Provides a more intuitive alternative to Select((element, index) => ...).
  2. Increases readability for index-dependent operations.

Benefits of the New LINQ Methods in .NET 9

1. Improved Readability: These methods reduce boilerplate code, making your queries more concise and expressive.

2. Enhanced Performance: Optimized implementations eliminate intermediate collections, improving efficiency in large datasets.

  1. Developer Productivity**: These additions reduce cognitive load, making common operations simpler and faster to implement.

Wrapping Up

.NET 9’s LINQ enhancements empower developers with tools that simplify data processing and improve performance.

Whether you’re counting occurrences, aggregating values, or working with indices, these new methods make your code cleaner and more efficient.

Start exploring Index, CountBy, and AggregateBy in your projects today!

Stay tuned for more insights into .NET 9 and beyond. If you’ve used these methods in a unique way, share your experiences with the community!

Check LINQ Performance Tips and Tricks.

That's all from me for today.

dream BIG!

About the Author

Stefan Djokic is a Microsoft MVP and senior .NET engineer with extensive experience designing enterprise-grade systems and teaching architectural best practices.

There are 3 ways I can help you:

1

Pragmatic .NET Code Rules Course

Stop arguing about code style. In this course you get a production-proven setup with analyzers, CI quality gates, and architecture tests — the exact system I use in real projects. Join here.

Not sure yet? Grab the free Starter Kit — a drop-in setup with the essentials from Module 01.

2

Design Patterns Ebooks

Design Patterns that Deliver — Solve real problems with 5 battle-tested patterns (Builder, Decorator, Strategy, Adapter, Mediator) using practical, real-world examples. Trusted by 650+ developers.

Just getting started? Design Patterns Simplified covers 10 essential patterns in a beginner-friendly, 30-page guide for just $9.95.

3

Join 20,000+ subscribers

Every Monday morning, I share 1 actionable tip on C#, .NET & Architecture that you can use right away. Join here.

Join 20,000+ subscribers who mass-improve their .NET skills with actionable tips on C#, Software Architecture & Best Practices.

Subscribe to
TheCodeMan.net

Subscribe to the TheCodeMan.net and be among the 20,000+ subscribers gaining practical tips and resources to enhance your .NET expertise.