I am populating an array with instances of a class:
BankAccount[] a;
. . .
a = new BankAccount[]
{
new BankAccount("George Smith", 500m),
new BankAccount("Sid Zimmerman", 300m)
};
Once I populate this array, I would like to sort it by balance amounts. In order to do that, I would like to be able to check whether each element is sortable using IComparable
.
I need to do this using interfaces. So far I have the following code:
public interface IComparable
{
decimal CompareTo(BankAccount obj);
}
But I'm not sure if this is the right solution. Any advice?
An alternative is to use LINQ and skip implementing IComparable altogether:
IComparable
already exists in .NET with this definition of CompareToYou are not supposed to create the interface -- you are supposed to implement it.
If you only need to sort these
BankAccounts
, useLINQ
like followingYou should not define IComparable yourself. It is already defined.
Rather, you need to implement IComparable on your
BankAccount
class.Where you defined the
class BankAccount
, make sure it implements the IComparable interfaceThen write
BankAccout.CompareTo
to compare the balance amounts of the two objects.Edit
Edit 2 to show Jeffrey L Whitledge's good answer:
There is already
IComparable<T>
, but you should ideally support bothIComparable<T>
andIComparable
. Using the inbuiltComparer<T>.Default
is generally an easier option.Array.Sort
, for example, will accept such a comparer.Do you want to destructively sort the array? That is, do you want to actually change the order of the items in the array? Or do you just want a list of the items in a particular order, without destroying the original order?
I would suggest that it is almost always better to do the latter. Consider using LINQ for a non-destructive ordering. (And consider using a more meaningful variable name than "a".)