Search code examples
c#linqsystem.io.fileinfo

Group Files into 500MB chunks


I have a List<FileInfo> of files

List<FileInfo> files = GetFiles();

which has about 2 GB of files. Now I need to chunk these files into 500MB parts. In this case the result will be 4 List<FileInfo> with the Sum of all Files is below 500MB. I have no Idea how to apply Sum() on this..

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

Solution

  • Here is something that works.

    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 });
    });