1

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.

4

2 回答 2

0

问题是 ArrayList 返回对象。对象不实现 IComparable。

因此,当您说 popList[i2].CompareTo(blah) 时,您正在调用不存在的对象上的函数。

于 2011-09-15T14:27:50.237 回答
0

IComparable是您在您希望能够...可比较的类上实现的接口。Sort 方法一开始就知道如何使用 IComparable 接口。因此,如果您想使用 Sort 方法进行排序,则您的类必须实现IComparable否则,当您调用CompareTo您的类时,您希望排序算法如何知道您的类在逻辑上是如何排序的?

这是有关如何工作的一些背景知识IComparable,但除非我误读,否则这似乎不是问题所在。看起来您正在尝试:

  1. OrderedByPopularity用一堆整数填充。
  2. 对整数进行排序。

如果你真的想对列表中的整数进行排序,你应该只需要使用

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

(这是 中的int元素类型List)已经有CompareTo它了。

这能回答问题吗?

于 2011-09-15T14:30:04.863 回答