Home > Mobile >  LinQ To group files by extension and get File sizes
LinQ To group files by extension and get File sizes

Time:12-04

I am trying to write a C# LinQ code to group the files by extension and compute the sizes and the total number of each extension.

For example, I have files = [a.txt, b.xml, c.html, d.doc, e.txt, f.pdf, g.docx];

I want to get:

|Extension| Count| Size|

txt | 2 | 24kb

doc | 2 | 16kb

html | 1 | 10b

xml | 1 | 8b

Here is my current code

var group = files.Select(file => Path.GetExtension(file)
                            .TrimStart('.').ToLower())
                            .GroupBy(y => y, (type, typecount) => new
                             {
                                 Type = type,
                                 Count = typecount.Count(),
                                 Size = new FileInfo(type).Length
                             })
                           .OrderBy(e=>e.Type);

It is not working as expected. Any help will be appreciated.

CodePudding user response:

To be able to sum the sizes, you must not select for the extension too early as you need the individual file names later to determine the size. I suggest the following:

var group = files
    .GroupBy(file => Path.GetExtension(file).ToLower().TrimStart('.'))
    .Select(g => new { Type = g.Key, Count = g.Count(), Size = g.Sum(file => new FileInfo(file).Length)})
    .OrderBy(e => e.Type);

The first line groups the file names by extension. The second line constructs the desired data.

  • Related