C#: Implementing IComparer for FileInfo objects (for binary searching and sorting)

While coding a thingie in C# that will optimize Acrobat Reader automatically I came across the need for interal overriding. More specifically I wanted to do a List.BinarySearch and my List was filled with FileInfo objects. Since one can compare files (for sorting and searching) in so many ways, you’re left on your own to subclass / override with the interface IComparer.

I found a neat example at http://www.mattandchristy.com/post/2008/02/Custom-Sorting-In-C-Sharp.aspx that shows just how easy it is to implement a custom IComparer.

My solution:


internal class PathCompare : IComparer
{
public int Compare(FileInfo o1, FileInfo o2)
{
return o1.FullName.CompareTo(o2.FullName);
}
}

Of course, this could be changed if you wanted to compare bytes, dates or whatever. My binary search was then executed like this:


myList.BinarySearch(myFile, new PathCompare());

Hooray!

Post to Twitter

| December 16th, 2008 | Posted in C#, Tips and tricks |

Leave a Reply