Bruce suggested that we use LINQ to sort collections. I found the following code on Miron Abrahason's blog but haven't had the chance to try it out yet.
This is how it can be done:
public static IEnumerable Sort(this IEnumerable source, string sortExpression)
{
string[] sortParts = sortExpression.Split(' ');
var param = Expression.Parameter(typeof(T), string.Empty);
try
{
var property = Expression.Property(param, sortParts[0]);
var sortLambda = Expression.Lambda>(Expression.Convert(property, typeof(object)), param);
if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
{
return source.AsQueryable().OrderByDescending(sortLambda);
}
return source.AsQueryable().OrderBy(sortLambda);
}
catch (ArgumentException)
{
return source;
}
}
Just drop it in a static class, and you will be able to sort any collection that implement the interface IEnumerable.
Lets say you have a class 'User':
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
and a List
IEnumerable sortedUsersIEnumerable = users.Sort("ID desc");
Or
List sortedUsersList = users.Sort("Name").ToList();
No comments:
Post a Comment