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");
Hi,
You can consider the dynamic linq libraries (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) that do something similar.
Otherwise calling the propertyInfo.GetValue() for each element is too slow imho, I would do it this way (30-40% faster):
public static IList OrderByName(this IList items, string order, string coloumn)
{
// don’t try to sort if we have no items
if (items.Count == 0) return items;
var sortExprParam = Expression.Parameter(typeof(T));
var sortExpr = Expression.Lambda<Func>(Expression.Property(sortExprParam, coloumn), sortExprParam).Compile();
return (order.ToUpper() == “ASC”
? items.OrderBy(sortExpr).ToList()
: items.OrderByDescending(sortExpr).ToList());
}
@Gaspar – Thanks for pointing out the dynamic linq libraries, really interesting stuff.
As for your suggestion where does the generic type come from here?
var sortExprParam = Expression.Parameter(typeof(T));
lol, nevermind just noticed that the comments squashed the generic input. My brain isn’t working too well.
I am trying to order a generic IList at runtime in C#
I used the code that you posted but didn’t work and got many errors! Can you provide me with sample running code? thanks!
public static IList<T> OrderByName<T, P>(this IList<T> items, string order, string column)
{
// don’t try to sort if we have no items
if (items.Count == 0) return items;
var sortExprParam = Expression.Parameter(typeof(T), column);
var sortExpr = Expression.Lambda<Func<T, P>>(Expression.Property(sortExprParam, column), sortExprParam).Compile();
return (
order.ToUpper() == “ASC”
? items.OrderBy(sortExpr).ToList()
: items.OrderByDescending(sortExpr).ToList()
);
}
public class DTO
{
public string Name { get; set; }
public int Value { get; set; }
}
var lst = new List<DTO>
{
new DTO{Name = “Jkl”, Value = 4},
new DTO{Name = “Def”, Value = 2},
new DTO{Name = “Ghi”, Value = 3},
new DTO{Name = “Abc”, Value = 1},
};
var lst1 = lst.OrderByName<DTO, string>(“desc”, “Name”);
var lst2 = lst.OrderByName<DTO, int>(“asc”, “Value”);