How do I sort an array of custom classes?

后端 未结 7 1039
暖寄归人
暖寄归人 2021-02-05 15:49

I have a class with 2 strings and 1 double (amount).

class Donator

  • string name
  • string comment
  • double amount

Now I have a A

7条回答
  •  暖寄归人
    2021-02-05 16:26

    By implementing IComparable and then use Array.Sort.

    public class Donator : IComparable {
        public string name;
        public string comment;
        public double amount;
    
        public int CompareTo(object obj) {
            // throws invalid cast exception if not of type Donator
            Donator otherDonator = (Donator) obj; 
    
            return this.amount.CompareTo(otherDonator.amount);
        }
    }
    
    Donator[] donators;  // this is your array
    Array.Sort(donators); // after this donators is sorted
    

提交回复
热议问题