DiskDiff: Sorting the Files

While using the application at this point, you may notice it’s tough to find the biggest files in the directory. It’d be nice to sort the files so they’re listed in order from largest to smallest.

A few chapters ago, you added a GetFiles() function to the DirectoryNode class. This junction returns an array of FileNode objects, so you can just sort the array before GetFiles() returns it, and that should give you the proper ordering. Nicely, the System .Array class has a Sort() member you can call to do the sorting.

For Sort() to work, it has to be able to figure out how to order the FileNode members. In the .NET Framework, you do this by implementing the IComparable<T> interface on FileNode. IComparable<T> has a member to compare two instances of T and returns integer values based on the ordering of the objects. The function for FileNode looks like this:

public int CompareTo(FileNode node2)


if (this.Size < node2.Size)


else if (this.Size > node2.Size)





The function compares the appropriate fields of the FileNode objects and returns the integer value. In this case, the CompareTo() function uses the Size property of the FileNode class; this simplifies the class a bit, though it does add a small bit of overhead because of the code in the get accessor of the property.

You then add the call to Array.Sort() in the GetFiles() function before the array is returned. That’s it! It’s so simple that you can add similar code to the DirectoryNode class so the directories are also sorted based on size.

One enhancement you could add is to allow the user to sort the files and directories either by directory or by file. See Chapter 30 for more information.

Source: Gunnerson Eric, Wienholt Nick (2005), A Programmer’s Introduction to C# 2.0, Apress; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *