Tuesday 5 July 2011

Generic IComparer to sort strings alphabetically

Sorting a list is one of the common tasks for a developer. It is handy to have a generic function to do this. See the example below. It sorts the employees by their name.


class Employee
{
public string Name { get; set; }
public string Email{ get; set; }
}

//Create Employee List
List<Employee> employees = new List<Employee>();
Employee emp = new Employee();
emp.Name = "Joe";
emp.Email= "joe@somewhere.com";
employees.add(emp);

emp = new Employee();
emp.Name = "Bell";
emp.Email= "bell@somewhere.com";
employees.add(emp);

//Sort Employee List albhabetically
employees.Sort(new GenericComparer());

//Generic IComparer to do the sorting
public class GenericComparer : IComparer<object>
{
public int Compare(object x, object y)
{
System.Collections.CaseInsensitiveComparer c = new System.Collections.CaseInsensitiveComparer();

if (x is Employee && y is Employee)
return c.Compare(((Employee)x).Name, ((Employee)y).Name);
else
throw new ArgumentException();
}
}

//You can replace the CaseInsensitiveComparer.Compare() call with the following line if you want to do a case-sensitive search
return string.Compare(((Employee)x).Name, ((Employee)y).Name);


Assume you have another List where Department is


class Department
{
public string Name { get; set; }
}


It will be handy if you can write something like the below line to sort the department list similar to the employee list.


departmentList.Sort(new GenericComparer());


Not a biggie. Just modify the Compare() function.


public int Compare(object x, object y)
{
System.Collections.CaseInsensitiveComparer c = new System.Collections.CaseInsensitiveComparer();

if (x is Employee && y is Employee)
return c.Compare(((Employee)x).Name, ((Employee)y).Name);
//Below condition is new
else if (x is Department&& y is Department)
return c.Compare(((Department)x).Name, ((Department)y).Name);
else
throw new ArgumentException();
}


Then you should be able to sort the department list successfully by calling
departmentList.Sort(new GenericComparer());

No comments:

Post a Comment