将文件分组为 500MB 的块

Group Files into 500MB chunks

我有 List<FileInfo> 个文件

List<FileInfo> files = GetFiles();

其中有大约 2 GB 的文件。现在我需要将这些文件分成 500MB 的部分。在这种情况下,结果将是 4 List<FileInfo>,所有文件的总和低于 500MB。我不知道如何在这上面应用 Sum()..

List<List<FileInfo>> result = files.GroupBy(x => x.Length / 1024 / 1014 < 500)
                                   .Select(x => x.ToList()).ToList();

这是有用的东西。

List<FileInfo> files = new List<FileInfo>();
List<List<FileInfo>> listOfLists= new List<List<FileInfo>>();
files.ForEach(x => {
     var match = listOfLists.FirstOrDefault(lf => lf.Sum(f => f.Length) + x.Length < 500*1024*1024);
     if (match != null)
         match.Add(x);
     else
         listOfLists.Add(new List<FileInfo>() { x });
});

这是您可以使用的通用 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();