gpt4 book ai didi

c# - 根据条件降序排列

转载 作者:太空狗 更新时间:2023-10-30 00:22:04 26 4
gpt4 key购买 nike

我想编写一个 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;
}
}

最佳答案

我认为您不能将条件放入较大的查询中,但您可以将其分离到另一个 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>();

关于c# - 根据条件降序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com