Generic Comparer for List

kgovindarao523-21772
Posted by kgovindarao523-21772 under LINQ category on | Points: 40 | Views : 2400
Hi,

This is generic class to sort the list with desiredcolumn with desired sorting order.

public sealed class GenericComparer<T> : IComparer<T>
{
public enum SortOrder {Ascending , Descending};

private string sortdirection;
private SortOrder SortingOrder;

public GenericComparer(string sortdirection, SortOrder SortingOrder)
{
this.SortingOrder= SortingOrder;
this.sortdirection=sortdirection;
}


public string SortColumn
{
get { return sortdirection; }
}
public SortOrder SortingOrder1
{
get { return SortingOrder; }
}

public int Compare(T x, T y)
{
PropertyInfo p = typeof(T).GetProperty(SortColumn);
IComparable o1 = (IComparable)p.GetValue(x, null);
IComparable o2 = (IComparable)p.GetValue(y, null);


if (SortingOrder1 == SortOrder.Ascending)
{
return (o1.CompareTo(o2));
}
else
{
return (o2.CompareTo(o1));
}
}
}

How to use:

if (sortdir == "Asc")
objList.Sort(new GenericComparer<T>(sortCol, GenericComparer<T>.SortOrder.Ascending));
else
objList.Sort(new GenericComparer<T>(sortCol, GenericComparer<T>.SortOrder.Descending));

Comments or Responses

Login to post response