This code snippet explains how to apply a user defined custom sort on a SortedList. The objects of the class to be sorted implements the IComparable interface and overrides the CompareTo()method. The code also takes the help of a customized comparer class which implements the IComparer interface.
Here is a BankAccount class on which we want to apply the custom sort. Different BankAccount objects will be stored on a SortedList with the BankAccount as the key and Account holder name as the value.
public class BankAccount : IComparable { long accountId; double balance; public BankAccount(long accountId, double balance) { this.accountId = accountId; this.balance = balance; } public long AccountId { get { return accountId; } } public double Balance { get { return balance; } } //Implement the ComparTo method; so that comparision is made using the bank balance field public int CompareTo(BankAccount other) { return Convert.ToInt32(balance - other.balance); } public override string ToString() { return "accountId=" + accountId + ", balance=" + balance; } }
Here is a BalanceComparer class which sorts the BankAccounts object in a descending order based on the balance:
public class BalanceComparer : IComparer { public int Compare(BankAccount x, BankAccount y) { return y.CompareTo(x); } }
Here is a test code to test the sort
SortedList accountList = new SortedList(); BankAccount account1 = new BankAccount(1001, 1500.00); BankAccount account2 = new BankAccount(1002, 1250.00); BankAccount account3 = new BankAccount(1003, 1750.00); accountList = new SortedList(new BalanceComparer()); accountList.Add(account1, "Dick"); accountList.Add(account2, "Eric"); accountList.Add(account3, "Bob"); for (int i = 0; i < accountList.Count; i++) Console.WriteLine("accountList[{0}]={1}", accountList.Keys[i], accountList.Values[i]);
|
No responses found. Be the first to respond and make money from revenue sharing program.
|