using Newtonsoft.Json.Linq;
using System.Collections.Generic;
public Payment(int accountId) => AccountId = accountId;
public static IEnumerable<Payment[]> GetBatches(IEnumerable<Payment> source, int count)
var hashset = new HashSet<int>(count);
var batch = new List<Payment>(count);
var leftOvers = new Queue<Payment>();
foreach (var item in source)
if (hashset.Add(item.AccountId))
while (batch.Count == count)
yield return batch.ToArray();
while (leftOvers.Any() && batch.Count != count)
if (hashset.Add(leftOvers.Peek().AccountId))
batch.Add(leftOvers.Dequeue());
if(batch.Any()) yield return batch.ToArray();
if (!leftOvers.Any()) break;
source = leftOvers.ToList();
public static void Main()
var list = new List<Payment>()
{new(1), new(2), new(3), new(4), new(4), new(5), new(6), new(4), new(4), new(6), new(4)};
var batches = GetBatches(list, 3);
foreach (var batch in batches)
Console.WriteLine(string.Join(", ", batch.Select(x => x.AccountId)));