Created
March 24, 2018 06:03
-
-
Save secretorange/50470c53d37be10f5f222d449cd6e817 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Text; | |
namespace SecretOrange.Data | |
{ | |
public class EasySort<T> where T : class | |
{ | |
private readonly IDictionary<string, Expression<Func<T, object>>> KeySelectors; | |
public EasySort() | |
{ | |
KeySelectors = new Dictionary<string, Expression<Func<T, object>>>(); | |
} | |
public EasySort(IDictionary<string, Expression<Func<T, object>>> keySelectors) | |
{ | |
KeySelectors = keySelectors; | |
} | |
public EasySort<T> Map(string key, Expression<Func<T, object>> keySelector) | |
{ | |
KeySelectors.Add(key, keySelector); | |
return this; | |
} | |
public IQueryable<T> Sort(IQueryable<T> query, string key, Order order) | |
{ | |
Expression<Func<T, object>> sort; | |
if (KeySelectors.ContainsKey(key)) | |
{ | |
sort = KeySelectors[key]; | |
if (order == Order.Desc) | |
{ | |
query = query.OrderByDescending(sort); | |
} | |
else | |
{ | |
query = query.OrderBy(sort); | |
} | |
} | |
return query; | |
} | |
} | |
public enum Order | |
{ | |
Unknown, | |
Asc, | |
Desc | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: