开发者

How do I sort an array of custom classes?

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

class Donator

Now I have a Array of Donators filled.

How I can sort by Amount?


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));


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;
}


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


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; );


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


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); });


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜