Phase 12 of 30 · Topic 12.3

Modern LINQ Operations: `Chunk`, `Zip`, `Index`, `Order` (.NET 6/7/8/9)

1Concept

.NET 9 introduces powerful LINQ primitives including `.Chunk()` for batching, `Index()` for zero-allocation tuples `(Index, Item)`, and non-allocating sorting.

2Architecture Diagram

[ 1, 2, 3, 4, 5, 6, 7 ] ──> .Chunk(3) ──> [ [1,2,3], [4,5,6], [7] ]
(Ideal for database batch insertion and microservice pagination!)

3Code Example

C# 13 & .NET 9
using System;
using System.Collections.Generic;
using System.Linq;

public class ModernLinqDemo
{
    public static void Main()
    {
        int[] dataset = [10, 20, 30, 40, 50, 60, 70];

        // 1. Chunking into batches of 3
        Console.WriteLine("--- Chunking Batches ---");
        foreach (var batch in dataset.Chunk(3))
        {
            Console.WriteLine($"Batch: [{string.Join(", ", batch)}]");
        }

        // 2. C# 13 Index() operator
        Console.WriteLine("--- Indexed Iteration ---");
        string[] techs = ["DotNet", "FastAPI", "Kubernetes"];
        foreach (var (idx, val) in techs.Select((item, i) => (i, item)))
        {
            Console.WriteLine($"[{idx}]: {val}");
        }
    }
}

4Expected Output

--- Chunking Batches ---
Batch: [10, 20, 30]
Batch: [40, 50, 60]
Batch: [70]
--- Indexed Iteration ---
[0]: DotNet
[1]: FastAPI
[2]: Kubernetes

5Key Takeaways

  • `.Chunk(batchSize)` replaces custom chunking extension methods.
  • Use `Enumerable.Order()` and `OrderDescending()` for direct comparable sorts.
  • Use `.MaxBy(x => x.Prop)` and `.MinBy()` for cleaner O(N) extreme queries.