IntroductionLet's say I create an EmployeeMaster class and an EmpoyeeCollection class based on the EmployeeMaster type. The EmployeeCollection class Inherit from the CollectionBase class. CodeSnippetThen now I’m going to implement the IComparer interface to compare two objects attributes like below. public class EmployeeMaster
{public EmployeeMaster(){}public EmployeeMaster(string _name, string _email, string _phone){this.name = _name;this.email = _email;this.phone = _phone;}string name;public string Name{get { return name; }set { name = value; }}string email;public string Email{get { return email; }set { email = value; }}string phone;public string Phone{get { return phone; }set { phone = value; }}}Create an collection inherit from collectionBase class. public class EmployeeCollection : CollectionBase
{public void SortByName(){IComparer comparer = new NameSortHelper();InnerList.Sort(comparer);}public void Add(EmployeeMaster employee){InnerList.Add(employee);}private class NameSortHelper : IComparer{#region IComparer Memberspublic int Compare(object x, object y){EmployeeMaster oEmployee1 = (EmployeeMaster)x;EmployeeMaster oEmployee2 = (EmployeeMaster)y;return oEmployee1.Name.CompareTo(oEmployee2.Name);}#endregion}} How to use the codeusing System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class SortCollectionDemo : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e){EmployeeCollection collection = new EmployeeCollection();collection.Add(new EmployeeMaster("RRavee", "rav@myemail.com", "834656756757"));collection.Add(new EmployeeMaster("KKumar", "kumar@myemail.com", "4654354343"));collection.Add(new EmployeeMaster("JJohn", "john@myemail.com", "543543435"));collection.Add(new EmployeeMaster("BBill", "bill@myemail.com", "324567577"));collection.Add(new EmployeeMaster("DDavid", "david@myemail.com", "867657465"));collection.SortByName();string namelist=string.Empty ;foreach (EmployeeMaster var in collection){namelist += "<br/>" + var.Name;}Response.Write(namelist);}}I hope this help to you all,when you are use the custom collection in your application. just copy this code and use it with your own object or class. |