Linq To Sql - 动态OrderBy - 案例何时

时间:2010-01-06 13:28:41

标签: linq linq-to-sql dynamic sql-order-by

我正在使用 Linq to sql Linq Dynamic OrderBy。

我知道linq dynamic可以像 - orderby(“column_name”)那样进行简单排序。

但是它是否支持更复杂的内容,例如带有“CASE WHEN”的查询?

string orderbyQuery = "(CASE WHEN (username == 100) THEN 1 ELSE 0 END) DESC)";

这是我的查询:

var u = from u in db.users
        orderby(orderbyQuery)
        select u;

上面的例子不起作用! ,任何想法,如果它可能吗? 还有其他办法吗?

感谢

3 个答案:

答案 0 :(得分:11)

var u = from u in db.users
        orderby u.username == 100 ? 1 : 0 descending
        select u;

答案 1 :(得分:1)

这对我很有用:

var queryResult = 
   from o in Source
   orderby (o.ColumnThatSaysOrderByColumn1 ? o.Column1 : o.Column2) descending
   select o

希望这有帮助!

答案 2 :(得分:0)

我创建了具有此类功能的扩展方法。它也可以通过将订单作为sql传递给ORDER BY CASE WHEN..THEN..

与Entity Framework一起使用
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