Я создал метод расширения с такими функциями. он также работает с Entity Framework, передавая заказ в sql
как ORDER BY CASE WHEN..THEN..
public static Expression<Func<TEntity, int>> CustomSortOrder<TEntity>(this IList<string> customSortOrderValues, string propName) {
var e = Expression.Parameter(typeof(TEntity), "e");
var prop = typeof(TEntity).GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
var eDotProp = Expression.MakeMemberAccess(e, prop);
var maxLen = customSortOrderValues.Count;
Expression ElseExpression(IList<string> values) {
var value = values[0];
var condition = Expression.Equal(eDotProp, Expression.Constant(value));
var ifTrue = Expression.Constant(maxLen - values.Count);
Expression ifFalse ;
if (values.Count == 1) {
ifFalse = Expression.Constant(maxLen - values.Count + 1);
}
else {
values.RemoveAt(0);
ifFalse = ElseExpression(values);
}
return Expression.Condition(condition, ifTrue, ifFalse);
}
return Expression.Lambda<Func<TEntity, int>>(
ElseExpression(customSortOrderValues),
e);
}
и скажем, что наша модель:
public class Cat{
public string Name {get;set;}
public Cat(string name){
Name = name;
}
использование ...
var cats = new List<Cat> { new Cat("cat1"), new Cat("cat2"), new Cat("cat3") };
var customSort = new List<string> { "cat2", "cat1", "cat3" }.CustomSortOrder<Cat>("Name");
var customOrderCats = cats.AsQueryable().OrderBy(customSort); // can work with Entity framework too //orders cat2,cat1,cat3