DEV Community

Cover image for Discovering the new LINQ methods in C# 9
AlpacaAppsDev
AlpacaAppsDev

Posted on • Originally published at alpacaappsdev.blogspot.com

4 1 1 1

Discovering the new LINQ methods in C# 9

Hey there! If you're a C# enthusiast like me, you're probably always on the lookout for the latest and greatest features in the language. Well, C# 9 has some fantastic new LINQ (Language Integrated Query) methods that are sure to make your coding life easier and more enjoyable. Let's dive into these new methods: CountBy, AggregateBy, and Index.

CountBy: Grouping Made Simple

First up, we have the CountBy method. This handy addition allows you to group elements by a specified key and then count the occurrences within each group. It's perfect for those times when you need to quickly determine the frequency of items in a collection.

Imagine you have a list of people with their first names, and you want to know how many people share the same name. Here's how you can do it with CountBy:

public record Person(string FirstName, string LastName);

List<Person> people = new()
{
    new("Steve", "Jobs"),
    new("Steve", "Carell"),
    new("Elon", "Musk")
};

foreach (var group in people.CountBy(p => p.FirstName))
{
    Console.WriteLine($"There are {group.Value} people with the name {group.Key}");
}
Enter fullscreen mode Exit fullscreen mode

This code will output:

There are 2 people with the name Steve
There are 1 people with the name Elon
Enter fullscreen mode Exit fullscreen mode

Pretty neat, right? It makes grouping and counting a breeze!

AggregateBy: Custom Aggregations

Next, let's talk about the AggregateBy method. This one takes the functionality of CountBy a step further by allowing you to perform custom aggregations on grouped elements. You can provide a seed value and an aggregation function to combine the elements in each group.

For example, let's say you have a list of people with an additional numeric property, and you want to sum these numbers for each group:

public record Person(string FirstName, string LastName, int SomeNumber);

List<Person> people = new()
{
    new("Steve", "Jobs", 10),
    new("Steve", "Carell", 100),
    new("Elon", "Musk", 10)
};

var aggregated = people.AggregateBy(
    person => person.SomeNumber,
    0,
    (acc, person) => acc + person.SomeNumber
);

foreach (var group in aggregated)
{
    Console.WriteLine($"Sum of SomeNumber for key {group.Key} is {group.Value}");
}
Enter fullscreen mode Exit fullscreen mode

This will output:

Sum of SomeNumber for key 10 is 20
Sum of SomeNumber for key 100 is 100
Enter fullscreen mode Exit fullscreen mode

With AggregateBy, you can easily perform complex aggregations without breaking a sweat.

Index: Accessing Items with Indices

Last but not least, we have the Index method. This method allows you to retrieve each item in a collection along with its index. It's super useful when you need to process items based on their position in the collection.

Here's an example of how you can use the Index method:

public record Person(string FirstName, string LastName);

List<Person> people = new()
{
    new("Steve", "Jobs"),
    new("Steve", "Carell"),
    new("Elon", "Musk")
};

foreach (var (index, person) in people.Index())
{
    Console.WriteLine($"Entry {index}: {person}");
}
Enter fullscreen mode Exit fullscreen mode

This will output:

Entry 0: Person { FirstName = Steve, LastName = Jobs }
Entry 1: Person { FirstName = Steve, LastName = Carell }
Entry 2: Person { FirstName = Elon, LastName = Musk }
Enter fullscreen mode Exit fullscreen mode

The Index method makes it easy to work with both the items and their positions in a collection.

Wrapping Up

The new LINQ methods in C# 9—CountBy, AggregateBy, and Index—are powerful tools that simplify common tasks and provide more flexibility in how you process collections. Whether you're counting items, performing custom aggregations, or retrieving items with their indices, these methods enhance the LINQ experience and make your code more expressive and concise.

So, go ahead and give these new methods a try in your next project. Happy coding!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (2)

Collapse
 
stevsharp profile image
Spyros Ponaris

This project enhances LINQ to Objects with extra methods, in a manner which keeps to the spirit of LINQ.
Check out MoreLINQ on github.com/morelinq/MoreLINQ .

Collapse
 
stevsharp profile image
Spyros Ponaris

Thanks for sharing!
The LINQ methods CountBy, AggregateBy, and Index are are excellent extensions provided by LINQ

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay