我想写一个LINQ to Entity查询,它根据输入参数按升序或降序排序,有没有办法。 以下是我的代码。请建议。
public List<Hosters_HostingProviderDetail> GetPendingApproval(SortOrder sortOrder)
{
List<Hosters_HostingProviderDetail> returnList = new List<Hosters_HostingProviderDetail>();
int pendingStateId = Convert.ToInt32(State.Pending);
//If the sort order is ascending
if (sortOrder == SortOrder.ASC)
{
var hosters = from e in context.Hosters_HostingProviderDetail
where e.ActiveStatusID == pendingStateId
orderby e.HostingProviderName ascending
select e;
returnList = hosters.ToList<Hosters_HostingProviderDetail>();
return returnList;
}
else
{
var hosters = from e in context.Hosters_HostingProviderDetail
where e.StateID == pendingStateId
orderby e.HostingProviderName descending
select e;
returnList = hosters.ToList<Hosters_HostingProviderDetail>();
return returnList;
}
}
答案 0 :(得分:7)
我认为你不能在较大的查询中加入条件,但你能做的就是将它分成另一个C#语句,如下所示:
// Common code:
var hosters = from e in context.Hosters_HostingProviderDetail
where e.ActiveStatusID == pendingStateId;
// The difference between ASC and DESC:
hosters = (sortOrder == SortOrder.ASC ? hosters.OrderBy(e => e.HostingProviderName) : hosters.OrderByDescending(e => e.HostingProviderName));
// More common code:
returnList = hosters.ToList<Hosters_HostingProviderDetail>();
答案 1 :(得分:3)
您可以使用
进一步减少它var hosters = from e in context.Hosters_HostingProviderDetail
where e.ActiveStatusID == pendingStateId
select e;
if (sortOrder == SortOrder.ASC)
hosters = hosters.OrderBy(e => e.HostingProviderName);
else
hosters = hosters.OrderByDescending(e => e.HostingProviderName);
return hosters.ToList<Hosters_HostingProviderDetail>();