Tag Archives: Ienumerable

.NET 6 Yenilikleri – Chunk ile collection’ları eşit parçalara ayırma

.NET 6 ile birlikte hayatımıza giren yeniliklerden biri de IEnumerable.Chunk metodu.

.NET 5 ve öncesinde, collection’ları eşit sayıda elemanlar olacak şekilde parçalara ayırmak için 2 yöntem vardı.

Birincisi aşağıdaki gibi bir custom (veya extension) metod yazmak;

static List List T Split T (IList T source, int size)
{
    return source.Select((x, i) = new { Index = i, Value = x })
        .GroupBy(x => x.Index / size)
        .Select(x => x.Select(v = v.Value).ToList())
        .ToList();
}

İkincisi de MoreLINQ içerisinde bulunan Batch metodunu kullanmaktı.

var buckets = numbers.Batch(10);

.NET 6 ile gelen IEnumerable.Chunk metodu ile bu işlemi artık custom bir metoda veya bir nuget paketine ihtiyaç duymadan halledebiliyoruz.

IEnumerable int numbers = Enumerable.Range(1, 34);
IEnumerable int[] buckets = numbers.Chunk(10);

foreach (int[] bucket in buckets)
{
    Console.WriteLine($"{bucket.First()} {bucket.Last()}");
}

Sonuç:

1 10
11 20
21 30
31 34

Kaynak: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.chunk