Last active
October 12, 2015 19:07
-
-
Save developerdizzle/4073070 to your computer and use it in GitHub Desktop.
Dynamic OrderBy (similar to SQL ORDER BY)
This file contains 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
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string sortExpression) | |
{ | |
IEnumerable<T> sortedItems = items; | |
Action<string> orderBy = delegate(string orderByExpression) { | |
string[] temp = orderByExpression.Split(' '); | |
string property = String.Empty; | |
string direction = String.Empty; | |
if (temp.Length > 0) | |
{ | |
property = temp[0]; | |
} | |
if (temp.Length > 1) | |
{ | |
direction = temp[1]; | |
} | |
if (!String.IsNullOrEmpty(property)) { | |
if (direction.ToUpper() == "DESC") | |
{ | |
sortedItems = sortedItems.OrderByDescending(r => GetPropertyValue(r, property)); | |
} | |
else | |
{ | |
sortedItems = sortedItems.OrderBy(r => GetPropertyValue(r, property)); | |
} | |
} | |
}; | |
string[] orderbys = sortExpression.Split(','); | |
foreach (string orderby in orderbys.Reverse()) | |
{ | |
orderBy(orderby.Trim()); | |
} | |
return sortedItems; | |
} | |
private static object GetPropertyValue(object item, string property) | |
{ | |
if (String.IsNullOrEmpty(property)) { return null; } | |
System.Reflection.PropertyInfo propertyInfo = item.GetType().GetProperty(property); | |
return propertyInfo.GetValue(item, null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment