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?
The IComparer interface is used to sort elements that compare two objects and provides additional comparison method.
This current instance occurs in the same position in the sort order as the object specified by the CompareTo method. This current instance follows the object specified by the CompareTo method in the sort order. All numeric types (such as Int32 and Double) implement IComparable, as do String, Char, and DateTime.
C# IComparable interfaceThe IComparable interface defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances. The IComparable is implemented by types whose values can be ordered or sorted. The interface requires the CompareTo method to be implemented.
IComparable is used to provide a default sort order for your objects. IComparer is to provide additional comparison mechanisms.
You 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
interface. Then write BankAccount.CompareTo
to compare the balance amounts of the two objects.
public class BankAccount : IComparable<BankAccount> { [...] public int CompareTo(BankAccount that) { if (this.Balance < that.Balance) return -1; if (this.Balance == that.Balance) return 0; return 1; } }
Edit to show Jeffrey L Whitledge's solution from comments:
public class BankAccount : IComparable<BankAccount> { [...] public int CompareTo(BankAccount that) { return this.Balance.CompareTo(that.Balance); } }
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".)
BankAccount[] bankAccounts = { whatever }; var sortedByBalance = from bankAccount in bankAccounts orderby bankAccount.Balance select bankAccount; Display(sortedByBalance);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With