Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with sort and IComparable

Tags:

c#

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?

like image 732
Trajanus Avatar asked Jul 20 '26 06:07

Trajanus


2 Answers

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.

like image 178
Jon Skeet Avatar answered Jul 27 '26 23:07

Jon Skeet


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);
like image 43
Konamiman Avatar answered Jul 27 '26 23:07

Konamiman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!