Ok, so Im only writing this blog post as a reference for myself so I dont have to think about it again, but hey it *may* be useful to someone but me.

I just needed to order a generic list based upon a property name string, here what I have:

public static IList<T> OrderByName<T>(this IList<T> items, string order, string coloumn)
{
 // don't try to sort if we have no items
 if (items.Count == 0) return items;
 var propertyInfo = typeof(T).GetProperties()
                             .Where(p => p.Name == coloumn)
                             .FirstOrDefault();
 return propertyInfo == null
    ? items
       : (order.ToUpper() == "ASC"
       ? items.OrderBy(n =>propertyInfo.GetValue(n, null)).ToList()
       : items.OrderByDescending(n => propertyInfo.GetValue(n, null)).ToList());
}

Usage:

myList.OrderByName("asc", "Property");
About these ads