Home > Mobile >  LINQ Query for File Types, Size, and Count
LINQ Query for File Types, Size, and Count

Time:11-24

I am currently trying to make a method that will create a query in C# LINQ that will give me the file type, the combined size of the file type, and the total amount of files of that type. I am struggling to get multiple columns and to have the query gather the file size. It seems to only work if I get the file size separately, but still can't seem to sum them up....

This one works getting the file size alone:

    var size = from f in files
               select (new FileInfo(f).Length);

but does not work here and I can't get the file count either:

        var all = from f in files
                  
                  group Path.GetExtension(f) by Path.GetExtension(f).ToLower() into fileGroup
                  select new {
                    Ext = fileGroup,
                    Byt = new FileInfo(fileGroup).Length
                  }; 

EDIT:

I was able to group by type & count, but still can't figure out how to add up the file sizes by their type:

    var info = files.Select(f => Path.GetExtension(f).ToLower()).GroupBy(x => x, (t, c) => new {
                                                                                                Extension = t,
                                                                                                Count = c.Count(),
                                                                                                Size = new FileInfo(x).Length

I am getting an error for the x

CodePudding user response:

First, I'm going to recommend you rename the method parameter to filePaths, because they are strings representing the paths. When you deal with a FileInfo object, that's better described as a "file".


You got close with the group by, the important thing is that the select afterwards is acting on the group's data.

I'm going to write this with extension methods.

var fileDataByExtension = filePaths
    .Select(fp => new FileInfo(fp))
    .GroupBy(f => f.Extension)
    .Select(group => new
    {
        Extension = group.Key,
        TotalBytes = group.Sum(f => f.Length),
        TotalFiles = group.Count()
    });
  1. Start with your collection of strings (filePaths)
  2. Turn all your strings into FileInfo objects up-front. It's a lot easier to extract the extension and size information from it.
  3. Group by the extension
  4. For each group (extension)
    • the Key is the extension (.txt, .exe, etc)
    • Sum up all the group's Lengths (the size of each file)
    • Count up all the group's entries

You now have an IEnumerable of anonymous objects.

CodePudding user response:

So "files" should be enumerable that has a count or size that contains the number of files.

 var size = from f in files
          select (new FileInfo(f).Length);
  • Related