Просто найденный ответом здесь http://github.com/leehambley/railsless-deploy :
ограничение deploy:rollback
My goal in this was to eliminate a lot of repetitious code. In addition to handling the ascending/descending my "OrderBy" function handles some other common logic has well. Assuming the function definition in the original posting, one can simply do this:
if ( {need to sort by integer})
query = OrderBy(objectT, a => a.myIntegerField, asc);
else if ( {need to sort by string})
query = OrderBy(objectT, a=> a.myStringField, asc);
:
Одно быстрое наблюдение: вам действительно не нужно использовать лямбда-выражение ( Expression
). Простой делегат ( Func
) подойдет.
Тем не менее, я думаю, что ответ, который вы, возможно, ищете, следующий:
Func<T,IComparable> func = null;
if (IsString)
func = (T a) => a.SomeStringValue;
else if (IsInt)
func = (T a) => a.SomeIntValue;
// call orderBy with exp
The expression can only have one type; my preferred answer here would be something like:
IQueryable<T> query = ...
if({case 1}) {
query = query.OrderBy(x=>x.SomeValue);
} else if({case 2}) {
query = query.OrderBy(x=>x.SomeOtherValue);
} ...
However, if you want to do something more flexible, you'd probably need to get into custom Expression
writing; something more like this.
Я думаю, что вы, возможно, ищете возможность иметь динамическое предложение orderby в linq. Некоторые хорошие статьи по этой теме см. В
или
http://www.equivalence.co.uk/archives/819
или
http://www.rocksthoughts.com/blog/archive/2008/01/24/linq-to -sql-dynamic-query.aspx