How do I sort an array of custom classes?

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

    You can also use delegates:

    class Program
    {
        static void Main(string[] args)
        {
            List<Donor> myDonors = new List<Donor>();
            // add stuff to your myDonors list...
    
            myDonors.Sort(delegate(Donor x, Donor y) { return x.amount.CompareTo(y.amount); });
        }
    }
    
    class Donor
    {
        public string name;
        public string comment;
        public double amount;
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-05 16:26

    Here is a sort without having to implement an Interface. This is using a Generic List

        List<Donator> list = new List<Donator>();
        Donator don = new Donator("first", "works", 98.0);
        list.Add(don);
        don = new Donator("first", "works", 100.0);
        list.Add(don);
        don = new Donator("middle", "Yay", 101.1);
        list.Add(don);
        don = new Donator("last", "Last one", 99.9);
        list.Add(don);
        list.Sort(delegate(Donator d1, Donator d2){ return d1.amount.CompareTo(d2.amount); });
    
    0 讨论(0)
  • 2021-02-05 16:34

    I always use the list generic, for example

    List<Donator> MyList;
    

    then I call MyList.Sort

    MyList.Sort(delegate (Donator a, Donator b) {
       if (a.Amount < b.Amount) return -1;
       else if (a.Amount > b.Amount) return 1;
       else return 0; );
    
    0 讨论(0)
  • 2021-02-05 16:35

    Another way is to create a class that implements IComparer, then there is an overload to pass in the Comparer class.

    http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx

    This way you could have different classes for each specific sort needed. You could create one to sort by name, amount, or others.

    0 讨论(0)
  • 2021-02-05 16:43

    You could use MyArray.OrderBy(n => n.Amount) providing you have included the System.Linq namespace.

    0 讨论(0)
提交回复
热议问题