我想提取一个OrderBy子句,这可能吗?
所以我可以这样做:
OrderBy ob = null;
if(....)
ob = x.Id
else
ob = x.Name
var result = source.OrderBy(ob);
这可能吗?
答案 0 :(得分:6)
您可以做一些几乎完全映射到您正在做的事情的事情,但更简单的选择是跟踪查询,而不是订购方法:
IQueryable<Whatever> query = someQuery;
if(something)
query = query.OrderBy(item => item.Id);
else
query = query.OrderBy(item => item.Name);
但是,如果你真的想:
Expression<Func<Whatever, object>> selector = null;
if(something)
selector = item => item.Id;
else
selector = item => item.Name;
var results = query.OrderBy(selector);
答案 1 :(得分:4)
您可以尝试这样的事情:
IQueryable<Foo> result = source ...
if(....)
result = result.OrderBy(x => x.Id);
else
result = result.OrderBy(x => x.Name);
答案 2 :(得分:0)
为什么不单独执行条件逻辑并根据条件执行单独的OrderBy()?
实施例
if(foo == true)
{
result = result.OrderBy(r => r.Id);
}
else
{
result = result.OrderBy(r => r.Name);
}