这是您可以使用的通用BatchBySize
扩展方法:
/// <summary>
/// Batches the source sequence into sized buckets.
/// </summary>
public static IEnumerable<TSource[]> BatchBySize<TSource>(
this IEnumerable<TSource> source,
Func<TSource, long> sizeSelector,
long maxSize)
{
var buffer = new List<TSource>();
long sumSize = 0;
foreach (var item in source)
{
long itemSize = sizeSelector(item);
if (buffer.Count > 0 && checked(sumSize + itemSize) > maxSize)
{
// Emit full batch before adding the new item
yield return buffer.ToArray(); buffer.Clear(); sumSize = 0;
}
buffer.Add(item); sumSize += itemSize;
if (sumSize >= maxSize)
{
// Emit full batch after adding the new item
yield return buffer.ToArray(); buffer.Clear(); sumSize = 0;
}
}
if (buffer.Count > 0) yield return buffer.ToArray();
}
使用示例:
List<FileInfo[]> result = files
.BatchBySize(x => x.Length, 500_000_000)
.ToList();