Created
January 4, 2013 14:02
-
-
Save ChrisMcKee/4452785 to your computer and use it in GitHub Desktop.
SortBy (Enumerable / Linq)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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