gpt4 book ai didi

c# - 在 LINQ 谓词中使用 OrderBy?

转载 作者:太空宇宙 更新时间:2023-11-03 19:30:00 25 4
gpt4 key购买 nike

在我的代码中,我需要按 PriceRating.TotalGrade 对集合进行排序,如您所见,这两个 LINQ 查询几乎是相同的语句,只有一个细微差别。

我正在考虑改用 LINQ 谓词,但如您所见,orderby 是主要区别,我发现没有在查询中使用 orderby 的示例。是否有可能或有其他方法可以缩短我的代码,也许将来会有更多条件。

if (CurrentDisplayMode == CRSChartRankingGraphDisplayMode.Position)
{
this.collectionCompleteSorted = new List<Result>(from co in collection
where co.IsVirtual == false
orderby co.Price, co.CurrentRanking
select co);
}
else if (CurrentDisplayMode == CRSChartRankingGraphDisplayMode.Grade)
{
this.collectionCompleteSorted = new List<Result>(from co in collection
where co.IsVirtual == false
orderby co.Rating.TotalGrade, co.CurrentRanking
select co);
}

最佳答案

您可以轻松地利用 LINQ 的延迟特性和轻松编写查询的能力。

可能使用这样的代码:

        var baseQuery = from co in collection where !co.IsVirtual select co; // base of query
IOrderedEnumerable<Result> orderedQuery; // result of first ordering, must be of this type, so we are able to call ThenBy

switch(CurrentDisplayMode) // use enum here
{ // primary ordering based on enum
case CRSChartRankingGraphDisplayMode.Position: orderedQuery = baseQuery.OrderBy(co => co.Price);
break;
case CRSChartRankingGraphDisplayMode.Grade: orderedQuery = baseQuery.OrderBy(co => co.TotalGrade);
break;
}

this.collectionCompleteSorted = orderedQuery.ThenBy(co => co.CurrentRanking).ToList(); // secondary ordering and conversion to list

它很容易理解并且避免了直到最后才转换为列表。

关于c# - 在 LINQ 谓词中使用 OrderBy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5623565/

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