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));