简体   繁体   English

如何提取order by子句,以便我可以使用逻辑来设置它?

[英]How to extract an order by clause so I can use logic to set it?

I want to extract out an OrderBy clause, is this possible? 我想提取一个OrderBy子句,这可能吗?

So I can do something like: 所以我可以这样做:

OrderBy ob = null;

if(....)
  ob = x.Id
else
  ob = x.Name


var result = source.OrderBy(ob);

Is this possible? 这可能吗?

You could do something that would map almost exactly to what you're doing, but the easier option is to keep track of the query, not the method to order on: 您可以执行几乎完全映射到您正在执行的操作的操作,但更简单的选项是跟踪查询,而不是订购方法:

IQueryable<Whatever> query = someQuery;

if(something)
    query = query.OrderBy(item => item.Id);
else
    query = query.OrderBy(item => item.Name);

However, if you really want to: 但是,如果你真的想:

Expression<Func<Whatever, object>> selector = null;

if(something)
    selector = item => item.Id;
else
    selector = item => item.Name;

var results = query.OrderBy(selector);

You could try something like this: 你可以尝试这样的事情:

IQueryable<Foo> result = source ...
if(....)
  result = result.OrderBy(x => x.Id);
else
  result = result.OrderBy(x => x.Name);

Why not just do your conditional logic and do the separate OrderBy() based on the conditon? 为什么不单独执行条件逻辑并根据条件执行单独的OrderBy()?

Ex. 防爆。

if(foo == true)
{
result = result.OrderBy(r => r.Id);
}
else
{
result = result.OrderBy(r => r.Name);
}

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

相关问题 如何使用where子句进行选择? - How can I use a where clause to select? 如何延迟“热”任务以使它们能够按固定顺序进行处理 - How to delay 'hot' tasks so they can processed in a set order 如何在 Vista 上设置 smtp 以便我可以使用 System.Net.Mail? - How do I set up smtp on Vista so I can use System.Net.Mail? 我怎样才能订购点列表,以便绘制的线不相交? - How can I order a list of Points so that no lines drawn intersect? 如何在单例类上使用Moq,以便我们只能测试业务逻辑并忽略日志记录 - How to use Moq on singleton classes so that we can only test Business logic and ignore logging 如何在sql中使用“HAVING”和“ORDER BY”子句 - How to use“ HAVING ”and “ORDER BY” clause in sql 我怎样才能让我的业务逻辑只执行一次,所以它只改变 object 一次 - How can i make my business logic only execute once, so it alters the object only once 我怎样才能概括这两个协程,所以我只使用一个? (在参数中输入一个布尔值并从内部设置) - How can I generalize these two coroutines so I only use one? (Input a boolean into the parameters and set from within) 如何在SQL查询中将变量用作子句? - How can I use a variable as a clause in sql query? 如何使用List &lt;&gt;作为Linq的where子句的条件? - How can I use a List<> as the condition for my where clause with Linq?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM