Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 14:02
Show Gist options
  • Save ChrisMcKee/4452785 to your computer and use it in GitHub Desktop.
Save ChrisMcKee/4452785 to your computer and use it in GitHub Desktop.
SortBy (Enumerable / Linq)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class LinqExtensions
{
public static IEnumerable<T> SortBy<T>(this IEnumerable<T> list, string sortExpression)
{
sortExpression += string.Empty;
string[] parts = sortExpression.Split(' ');
if (parts.Length > 0 && parts[0] != string.Empty)
{
string property = parts[0];
bool descending = false;
if (parts.Length > 1)
{
descending = parts[1].ToLower().Contains("esc");
}
PropertyInfo prop = typeof(T).GetProperty(property);
if (prop == null)
{
throw new Exception(string.Format("No property '{0}' in + {1}'", property, typeof(T).Name));
}
if (descending)
return list.OrderByDescending(x => prop.GetValue(x, null));
return list.OrderBy(x => prop.GetValue(x, null));
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment