Haven't found a similar question
I want to slice an array into smaller batches based on byte size limit. This is my implementation which is a little slow. In particular I want to know if there is a build-in functionality that can get me this, or maybe I can enhance my approach below.
When i accumulated the size of individual items it didn't correlate correctly to the size of the batch. probably extra metadata on the stream itself..
private static List<List<T>> SliceLogsIntoBatches<T>(List<T> data) where T : Log
{
const long batchSizeLimitInBytes = 1048576;
var batches = new List<List<T>>();
while (data.Count > 0)
{
var batch = new List<T>();
batch.AddRange(data.TakeWhile((log) =>
{
var currentBatchSizeInBytes = GetObjectSizeInBytes(batch); // this will slow down as takewhile moves on
return (currentBatchSizeInBytes < batchSizeLimitInBytes);
}));
batches.Add(batch);
data = data.Except(batch).ToList();
}
return batches;
}
private static long GetObjectSizeInBytes(object objectToGetSizeFor)
{
using (var objectAsStream = ConvertObjectToMemoryStream(objectToGetSizeFor))
{
return objectAsStream.Length;
}
}