DEV Community

Cover image for Como "fatiar" ("chunk") Lists ou Enumerable em pedaços menores em C#
João Batista Costa Oliveira
João Batista Costa Oliveira

Posted on

5 3

Como "fatiar" ("chunk") Lists ou Enumerable em pedaços menores em C#

Hoje vou compartilhar um pequeno trecho de código em C# que permite que você "fatie" ou (crie um "chunk" de) uma lista em n listas menores utilizando Linq.

O código "fatia" um Enumerable em C# em um tamanho especificado, se a lista dada não puder ser dividida uniformemente, o pedaço final conterá os elementos restantes.

using System.Collections.Generic;
using System.Linq;

public static class ListHelper{
  public static List<List<T>> ChunkList<T>(IEnumerable<T> data, int size)
  {
    return data
      .Select((x, i) => new { Index = i, Value = x })
      .GroupBy(x => x.Index / size)
      .Select(x => x.Select(v => v.Value).ToList())
      .ToList();
  }
}

//Exemplo
List<int> numList = new List<int> { 1, 2, 3, 4, 5 }; 
ListHelper.ChunkList(numList, 3); // { {1, 2, 3}, {4, 5} }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay