How do I sort an array of custom classes?

后端 未结 7 1018
暖寄归人
暖寄归人 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:44

    If you implement IComparable<Donator> You can do it like this:

    public class Donator :IComparable<Donator>
    {
      public string name { get; set; }
      public string comment { get; set; }
      public double amount { get; set; }
    
      public int CompareTo(Donator other)
      {
         return amount.CompareTo(other.amount);
      }
    }
    

    You can then call sort on whatever you want, say:

    var donors = new List<Donator>();
    //add donors
    donors.Sort();
    

    The .Sort() calls the CompareTo() method you implemented for sorting.

    There's also the lambda alternative without IComparable<T>:

    var donors = new List<Donator>();
    //add donors
    donors.Sort((a, b) => a.amount.CompareTo(b.amount));
    
    0 讨论(0)
提交回复
热议问题