38. Directory size, LINQ style

Both this solution and Solution 30. Directory size, use the DirectoryInfo class's GetFiles method to make an array holding FileInfo objects that represent the files contained within the directory. The previous solution then used the following code to add the files' sizes:

// Add the file sizes.
long size = 0;
foreach (FileInfo fileinfo in fileinfos) size += fileinfo.Length;
return size;

This code loops through FileInfo objects and adds their file lengths to the size variable.

The new SizeLINQ extension method uses the following code to perform the same task:

// Add the file sizes.
var sizeQuery =
from FileInfo fileinfo in fileinfos
select fileinfo.Length;
return sizeQuery.Sum();

This version creates a LINQ query that loops through the FileInfo objects and selects their Length values. The program then invokes the query's Sum LINQ extension method to add the selected length values.

Which version you should use is largely a matter of personal preference. LINQ programs are often slower than other methods because they don't take advantage of any special structure that's available in the data. In this example, however, the time needed to calculate a directory's size is dominated by the time it takes to access the disk, not the time needed to process the results. In one set of tests, the LINQ version of this program took only a little while longer than the non-LINQ version.

What this means is that, in cases like this where LINQ has a negligible performance impact, you should pick whichever approach makes the code easier for you to read and understand.

Download the DirectorySizeLINQ example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.62.34