I have a class with 2 strings and 1 double (amount).
class Donator
Now I have a A
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
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); });
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; );
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.
You could use MyArray.OrderBy(n => n.Amount)
providing you have included the System.Linq namespace.