CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

GenericSorter<T>

304 Views
Copy Code Show/Hide Line Numbers
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Linq.Expressions; 
 
 
public class GenericSorter<T>
{
    public IEnumerable<T> Sort(IEnumerable<T> source, string sortBy, string sortDirection)
    {
        var param = Expression.Parameter(typeof(T), "item");
 
        var sortExpression = Expression.Lambda<Func<T, object>>
            (Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param);
 
        switch (sortDirection.ToLower())
        {
            case "asc":
                return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);
            default:
                return source.AsQueryable<T>().OrderByDescending<T, object>(sortExpression);
 
        } 
    }
}
by Athens Springer
  October 29, 2009 @ 9:11am
Tags:
Description:
Usage:
GenericSorter gs = new GenericSorter();
SurveyStateFormatItems = gs.Sort(SurveyStateFormatItems.AsQueryable, sortExpression, sortDirection).ToArray();

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate