简体   繁体   English

使用System.Linq.Dynamic的自定义排序顺序

[英]Custom Sort Order Using System.Linq.Dynamic

I have records that are given a class that i need to order by. 我有给定记录的类,需要对其进行排序。

The values are simple 0,1,2. 值是简单的0,1,2。 The problem is the client needs the records to appear in a order based on there class name not class value. 问题是客户需要记录以基于类名而不是类值的顺序显示。 The order should appear as seen below. 顺序应如下所示。

class (TBD)= 0
class (2/3)= 2 
class (1)= 1

Using System.Linq.Dynamic i have been able to pass columns and there direction into my OrderBy() . Using System.Linq.Dynamic我已经能够将列和方向传递到我的OrderBy() Is there a way to pass in a expression that would force the sort order to be 有没有一种方法可以传递将强制排序顺序为

Ascending: class (TBD)= 0, class (2/3)= 2 , class (1)= 1 升序:等级(TBD)= 0,等级(2/3)= 2,等级(1)= 1

Descending: class (1)= 1, class (2/3)= 2, class (TBD)= 0 降序:等级(1)= 1,等级(2/3)= 2,等级(TBD)= 0

I have tried asc: 我尝试了asc:

sort = "(Class = 0) desc, (Class = 2) desc, (Class = 1) desc";

desc: 说明:

sort = "(Class = 1) desc, (Class = 2) desc, (Class = 0) desc";

But i get Operator '=' incompatible with operand types 'String' and 'Int32' Before that i was using '==' and got a similar message. 但是我得到的Operator '=' incompatible with operand types 'String' and 'Int32'在此之前,我使用'=='并得到了类似的消息。

 searchUniq = searchUniq.OrderBy(sort).Skip(skip).Take(25);

Your string is not a valid sort syntax for Dynamic Linq. 您的字符串不是Dynamic Linq的有效排序语法。 Try: 尝试:

sort = "iif(Class == 1, 0, iif(Class == 2, 1, 2))";

This uses the inline if expression available in Dynamic Linq (at least one flavor of it; see here for more documentation) to transform the Class values into something intuitively orderable. 它使用Dynamic Linq中可用的内联if表达式(至少有其一种形式;请参见此处获取更多文档)将Class值转换为直观可排序的内容。 The vanilla SQL equivalent is to order by a case statement. 等效的vanilla SQL是按case语句排序的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM