Problems with sort and IComparable
I'm trying to sort an ArrayList
of custom items and get 'At least one object must implement IComparable.' despite having implemented the IComparable
interface for them. I'm just calling the default Sort()
no parameters or anything. The definition of the object I'm trying to sort is as follows:
class AssetItem : System.IComparable<AssetItem>
{
public string AssetName { get; set; }
public int AssetID { get; set; }
public int CompareTo(AssetItem item)
{
if (null == item)
{
return 1;
}
else if (this.AssetID < item.AssetID)
{
return -1;
}
else if (this.AssetID == item.AssetID)开发者_高级运维
{
return this.AssetName.CompareTo(item.AssetName);
}
else
{
return 1;
}
}
This code builds just fine. One more thing to keep in mind, and I suspect this may be the issue though I don't understand how, the class above is an inner class. If that is what's tripping me up, how would you go about comparing an inner class?
You've implemented IComparable<T>
, not IComparable
. They're different interfaces. If you're going to use generics, just use List<T>
to start with. I mean you could also implement IComparable
, but I'd just move away from the somewhat-obsolete nongeneric collections if I were you.
Can you use LINQ in your project? If so, and if all you need is sorting by a property, you don't need to implement IComparable. You could just do:
theAssetsList.OrderBy(asset => asset.AssetId);
You can also try.. list= new List(list.OrderBy(x => x.Text));
精彩评论