New LINQ methods in .NET 9.0

New LINQ methods in .NET 9

With .NET 9 and C# 13, the LINQ methods Index, CountBy and Aggregate were introduced. With these methods, it makes it a lot easier to perform complex data manipulations and aggregations. These new methods enhance the capabilities of LINQ, allowing developers to write more concise and readable code when working with collections.

  var products = new List<Product>()
    {
        new() { Name = "Laptop", Price = 899.99m, 
                Quantity = 5, Location = "Phoenix" },
        new() { Name = "Sunglasses", Price = 99.99m, 
                Quantity = 4, Location = "Tarzana" },
        new() { Name = "Clock", Price = 50m, 
            Quantity = 1, Location = "Phoenix" }
    };

Index

The Index LINQ method allows you to iterate through a list of collection while also retrieving the index value.

  • Given an IEnumerable, the Index returns a IEnumerable that consists of a tuple of index and item.
public static IEnumerable<(int Index, TSource Item)> Index<TSource>(this IEnumerable<TSource> source);

Below is the code sample:

foreach (var (idx, product) in products.Index())
{
  Console.WriteLine($"Index: {idx} Product: {product.Name}, Price: {product.Price}");
}

CountBy

The CountBy LINQ method groups elements by a key and counts the occurrences for each group. Prior to .NET 9 and C#13, this was achieved by using the GroupBy and Select methods. Now, it can be done straightforward with a single expression.

  • Given an IEnumerable, the Index returns a IEnumerable that consists of a key value pair of the key of the group and the count.
    public static IEnumerable<KeyValuePair<TKey,int>> CountBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector);
    

    Below is the code sample:

    var newCountsByLocation = products.CountBy(p => p.Location);
    
    foreach (var item in newCountsByLocation)
    {
        Console.WriteLine($"Location: {item.Key}, Count: {item.Value}");
    }
    
      foreach (var (location, count) in newCountsByLocation)
    {
        Console.WriteLine($"Location: {location}, Count: {count}");
    }
    

AggregateBy

In C# 13 and .NET 9 release, AggregateBy is a LINQ method used to aggregate results over a sequence of elements grouped by a key. This allows you to group and aggregate at the same time.

  • The first argument will be the key selector, which is the key by which the elements are grouped.
  • The second argument is the initial seed value.
  • The third argument is the func that defines the aggregation function and cumulatively performs the operation on every single element.
  public static IEnumerable<KeyValuePair<TKey,TAccumulate>> AggregateBy<TSource,TKey,TAccumulate>(this IEnumerable<TSource> source, 
                                                                                                  Func<TSource,TKey> keySelector, 
                                                                                                  Func<TKey,TAccumulate> seedSelector, 
                                                                                                  Func<TAccumulate,TSource,TAccumulate> func
                                                                                                  );

Below is the code sample:

var totalQuantityAndPriceByLocationAndCount = products.AggregateBy(
    product => product.Location,
    seed: (TotalQuantity: 0, TotalPrice: 0m, Count: 0),
    (totals, product) => (
        totals.TotalQuantity + product.Quantity,
        totals.TotalPrice + product.Price,
        totals.Count + 1
    )
);
Written by

Deepti

I'm Deepti Velusamy. I’m a software developer with a strong focus on backend API development (.NET) and extensive experience in AWS, terraform, micro services and containerization.