473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Confusion over how IComparer works

This is probably a newbie question but I'm really confused on how the IComparer works and I've looked for information online and offline. The code works, I just don't understand how.

I'm sorting an array that has only one element but the comparer has two arguments:

Expand|Select|Wrap|Line Numbers
  1. public int Compare(object a, object b)
  2. {
  3. yada yada
  4. }
I've stepped through the code and I can see that both object a and object b have values from the single-element array but I don't understand how that happens. Can anyone enlighten me?

Here is the associated code:

// files is simply a list of files returned by DirectoryInfo
Expand|Select|Wrap|Line Numbers
  1. sortByDateTime fCompare = new sortByDateTime();
  2. Array.Sort(files, fCompare)
  3.  
  4. private class sortByDateTime : IComparer<object>
  5.         {
  6.             public int Compare(object a, object b)
  7.             {
  8.                 FileInfo f1;
  9.                 FileInfo f2;
  10.                 f1 = (FileInfo)a;
  11.                 f2 = (FileInfo)b;
  12.                 return f2.LastWriteTime.CompareTo(f1.LastWriteTime);
  13.             }
  14.         }
thanks!
Aug 31 '09 #1
5 4454
tlhintoq
3,525 Expert 2GB
Realize you aren't sending to the Compare you wrote. You are calling the .Sort method of the Array class using the Compare as an argument you are sending.

The sort method in the Array class is then doing things you don't see. It is receiving two things: Your array and the compare method you wrote. It then loops through the array elements taking element 0 & 1 and sending them to the compareing, then 1&2, then 2&3 and so on... until it is done sending everything and every comparrison returns that it is in correct order.

Lines 10 and 11 presume that objects a and b are FileInfo objects and typecasts them in FileInfo objects F1 and F2.

Line 6 shows this method with return an int.
Line 12 compares the two LastWriteTime properties and returns the result of the comparison as an int. If I remember right that compare is something like
-1 means first item is greater than second item
0 means the two items are equal
+1 means the second item is greater than the first time
but look it up or confirm it through your own testing to be sure I don't have that backwards.
Aug 31 '09 #2
GaryTexmo
1,501 Expert 1GB
I'm not 100% sure since I've never implemented IComparer before, but if it's anything like operator overloading (and I hear it is), then the other value would be what it's compared too...

Expand|Select|Wrap|Line Numbers
  1. if (objA == objB) { ... }
Then right there are your a and b objects in your Compare method. A comparison (equality) always has two objects. The Array.Sort method takes a IComprarer implementation so it knows how to sort the list... that is, so it knows if something is equal (I would imagine you'd need greater and less than as well), and can thus sort your list.

It's the Array.Sort method that goes through the elements in the array and makes the comparisons, so that's what ends up as a and b in your method.
Aug 31 '09 #3
Thanks to both of you for your replies.

tlhintoq, you really explained things well and you're right, I didn't know what was going on behind the scenes. Makes a lot more sense now. How did you know that it takes element 0 & 1 then 1 & 2, etc. ? I can't seem to find information on it....
Aug 31 '09 #4
cloud255
427 Expert 256MB
How did you know that it takes element 0 & 1 then 1 & 2, etc. ?
The Array.Sort method uses the Quicksort Algorithm.

But one handy thing to remember when using IComparer is that you can customize exactly how the Compare method works so that you can compare any property (or several properties) of an object:

Expand|Select|Wrap|Line Numbers
  1. int IComparer.Compare(Object x, Object y)
  2.         {
  3.             FileInfo FIx = (FileInfo) x;
  4.             FileInfo FIy = (FileInfo) y;
  5.  
  6.             if ((FIx.CreationTime > (FIy.CreationTime)) && (FIx.LastAccessTime > FIy.LastAccessTime))
  7.                 return -1;
  8.             else if ((FIx.CreationTime < (FIy.CreationTime)) && (FIx.LastAccessTime < FIy.LastAccessTime))
  9.                 return 1;
  10.             else return 0;
  11.         }
  12.  
The example above is not really one that you would use, but is rather just to illustrate the extensibility of the Compare method.
Sep 1 '09 #5
cloud255....thanks!

After all the replies I am much more familiar with using IComparer. Thanks to everyone for your input.
Sep 1 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Cybertof | last post by:
Hello, Could someone please explain me the difference between the 2 interfaces IComparable and IComparer ? In which cases use one or the other ? Are they dedicated to own classes or built-in...
3
by: RJN | last post by:
Hi I have a user defined data type which implements IComparable interface and has an implementation for the CompareTo method. Public Class MyDataType Implements IComparable --Private...
10
by: INeedADip | last post by:
I am trying to use a generic (reflection) IComparer class to sort a generic list but I get the error: Unable to cast object of type 'GenericComparer' to type 'System.Collections.Generic.Icomparer...
1
by: INeedADip | last post by:
I am trying to use the following generic (reflection) class as the ICamparer parameter for a generic list..but I get the error: "Unable to cast object of type 'GenericComparer' to type...
4
by: Irfan | last post by:
hi, I am trying to arrange a CollectionOfCars in increasing order of their X-Cordinate location. CollectionOfCars is a generic collection. Dim CollectionOfCars as new list(of Car) Here is...
1
by: Brett Romero | last post by:
What are the reasons to use one over the other? SortedList implements IComparer.Compare(). Why would you also want to create a SortedList class that implements IComparable.CompareTo()? I know...
3
by: jtfaulk | last post by:
Re: ArrayList, Sort, Menu, IComparer, Object, multidemensional I have a multi-dimensional arraylist, and I would like to sort one level of it but not all. The multi-dimensional arraylist...
10
by: Tony | last post by:
Hello! I'm reading in a book and this can't be correct it says. "Objects passed to Comparer.Compare() are checked to see if they support IComparable. If they do, then that implementation is...
3
by: raylopez99 | last post by:
This is an example of using multiple comparison criteria for IComparer/ Compare/CompareTo for List<and Array. Adapted from David Hayden's tutorial found on the net, but he used ArrayList so the...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.