Sorting and IComparable issues

I am trying to sort ArrayList

custom items and get "At least one object must implement IComparable". despite having implemented an interface for them IComparable

. I just call the Sort()

default parameters or whatever. The definition of the object I'm trying to sort looks like this:

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 it might be a problem, although I don't understand how the class above is an inner class. If this is what turns me off, how would you compare the inner class?

+2


source to share


3 answers


You have implemented IComparable<T>

, not IComparable

. These are different interfaces. If you are going to use generics, just use List<T>

to get started. I mean you could implement as well IComparable

, but I would just move away from somewhat legacy collections if I were you.



+9


source


Can you use LINQ in your project? If so, and if all you want is sorts by property, then you don't need to implement IComparable. You could just do:



theAssetsList.OrderBy(asset => asset.AssetId);

      

+3


source


You can also try .. list = new List (list.OrderBy (x => x.Text));

0


source







All Articles