Getting Started with Adobe After Effects - Part 6: Motion Blur
This module helps you to share, discuss and learn interview questions and answers of different technologies

How to sort the data in generic list with specific attribute?

Dec 20 2011 11:02PM by Ramireddy   

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.

  1. Create a class with all the attributes and implement sort methods based on attributes in the class.
  2. After creating the collection, initialize the delegate and pass corrosponding methodname as parameter to delegate.
  3. 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 ·  ·  ·  · 


Ramireddy
2 · 41% · 12972
0
Liked
 
0
Asked



Submit

Your Comment


Sign Up or Login to post a comment.

"How to sort the data in generic list with specific attribute?" rated 5 out of 5 by 3 readers
How to sort the data in generic list with specific attribute? , 5.0 out of 5 based on 3 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]