While converting the list in batches, yield return skips object that has been checked in if condition but not added to bucket because of size constraints.
Total message count: 4
1st bucket count: 2
2nd bucket count: 1
3rd message from the message list is getting skipped.
Here I am creating buckets of size 250kb. Is there any other way to save the correct state or do I need to use for loop?
public static IEnumerable<IEnumerable<Message>> GetBatchSize(IList<Message> source)
{
List<Message> bucket = null;
long size = 0;
foreach (var item in source)
{
if (bucket == null)
{
bucket = new List<Message>();
}
size = size + item.Size;
if (250 - (size / 1024) >= item.Size / 1024)
{
bucket.Add(item);
continue;
}
yield return bucket;
bucket = new List<Message>();
size = 0;
}
if (bucket?.Count > 0 && size<250)
{
yield return bucket;
}
}