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

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: