Question
How to sort the data in generic list with specific attribute?
Answer
In .net framework 2.0, "Comparision" delegate has been introduced. By using this delegate,we can sort generic list based on specific attribute.
- Create a class with all the attributes and implement sort methods based on attributes in the class.
- After creating the collection, initialize the delegate and pass corrosponding methodname as parameter to delegate.
- Call Sort() method of generic list.
Defining Class:
public class Customer
{
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
private int _Age;
public int Age
{
get { return _Age; }
set { _Age = value; }
}
private int _CustomerID;
public int CustomerID
{
get { return _CustomerID; }
set { _CustomerID = value; }
}
public static int CompareCustomerID(Customer c1, Customer c2)
{
return c1.CustomerID.CompareTo(c2.CustomerID);
}
public static int CompareCustomerName(Customer c1, Customer c2)
{
return c1.CustomerName.CompareTo(c2.CustomerName);
}
public static int CompareCustomerAge(Customer c1, Customer c2)
{
return c1.Age.CompareTo(c2.Age);
}
}
Creating Collection and initializing delegate:
List<Customer> lstCustomers = new List<Customer>();
lstCustomers.Add(new Customer() { CustomerID = 10, CustomerName = "Ram", Age = 26 });
lstCustomers.Add(new Customer() { CustomerID = 5, CustomerName = "Reddy", Age = 35 });
lstCustomers.Add(new Customer() { CustomerID = 15, CustomerName = "Sam", Age = 15 });
Comparison<Customer> dlgCompare = new Comparison<Customer>(Customer.CompareCustomerID);
lstCustomers.Sort(dlgCompare);
Read More..
 
[32134 clicks]
Published under:
C# Interview Questions and Answers · · · ·