Search code examples
c#sortingcollectionscompact-framework2.0

Implementing IComparable using Framework 2.0


I am trying to refactor the below code for the 2.0 framework (required at work). The below code was kindly provided per a previous post in which I was trying to figure out how to sort a dictionary of arraylists. This is a bit of a tangent from that discussion. Below is the code:

 MultiDimDictList myDicList = new MultiDimDictList();
myDicList.Add("fly", a_fly);
myDicList.Add("img", a_img);
myDicList.Add("bar", a_bar);
myDicList.Add("meter", a_meter);
myDicList.Add("block", a_block);
myDicList.Add("popularity", a_pop); 

List<int> OrderedByPopularity = new List<int>();
ArrayList popList = myDicList["popularity"];

for (int i = 0; i < popList.Count; ++i)
{
    OrderedByPopularity.Add(i);
}

OrderedByPopularity.Sort((i1, i2) => 
{ 

    return popList[i2].CompareTo(popList[i1]); 

});

When I try to run the above code, the bottom-most logic is giving me problems - namely, that "CompareTo" is not recognized. I have done some reading up on this and it looks like I have to implement IComparable to get this to work but I could use some help / suggestions here. Where should I be implementing IComparable? Also, the compiler is also telling me to use "delegate" for my .Sort method. Am i right that it should look like: .Sort(delegate(int i1, int i2) => ?

Thanks for your help.


Solution

  • IComparable is an interface that you implement on a class that you want to be able to be...comparable. The Sort method knows how to work with the IComparable interface right off the bat. So, it follows that if you want to sort using the Sort method, your class must implement IComparable Otherwise, when you call CompareTo on your class, how would you expect the sorting algorithm to know how your class logically sorts?

    That is some background on how IComparable works, but it doesn't look like it is the problem here unless I am misreading. It looks like you are trying to:

    1. Fill OrderedByPopularity with a bunch of integers.
    2. Sort the integers.

    If you really want to sort the integers in your list, you should just need to use

    (i1, i2) => 
    { 
        return i1.CompareTo(i2); 
    }
    

    the int (which is the type of element in the List) already has CompareTo on it.

    Does this answer the question?