LINQ: Calculate Average File Size in C#

Let us see a simple code using LINQ and C# that calculates the average FileSize of the files kept in a folder.

First import the following namespaces:

using System.Linq;
using System.IO;

Then write the following code:

class Program
 static void Main(string[] args)
  string[] dirfiles = Directory.GetFiles("c:\\software\\");            
  var avg = dirfiles.Select(file =>  
                  new FileInfo(file).Length).Average();
  avg = Math.Round(avg/1000000, 1);
  Console.WriteLine("The Average file size is {0} MB",

The code shown above uses the Average Extension method to compute the average of a sequence of' numeric values. The values in this case is the length of the files in the folder “c:/software”. The result is rounded off to one decimal place using Math.Round

 LINQ Average File Size

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: