在我的代码中,我需要通过 Price 或 Rating.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);
}
答案 0 :(得分:3)
您可以轻松利用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
它很容易理解,并且避免转换到列表直到最后。
答案 1 :(得分:1)
如果只是你的订单不同,那么将结果返回到this.collectionCompleteSorted,然后在枚举数据时执行this.collectionCompleteSorted.OrderBy()。
this.collectionCompleteSorted = new List<Result>(from co in collection
where co.IsVirtual == false
select co);
foreach (var obj in this.collectionCompleteSorted.OrderBy(c => c.Price).ToList())
{
// do something
}
删除当前的linq查询,删除订单。
如果查询刚刚执行一次,那么您可以从上面示例中的linq查询中取消.ToList()。当调用ToList时,这会导致查询立即执行,如果OrderBy在稍后调用集合时实现,而ToList也是,那么查询实际上将在具有order by语句的数据库服务器上执行,将代码从代码卸载到数据库。见http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx
答案 2 :(得分:1)
为什么不抓住价值(减少排序),然后(如图所示)使用案例来订购结果?
// build your collection first
var items = from co in collection
where !co.IsVirtual
select co;
// go through your sort selectors
select (CurrentDisplayMode)
{
case CRSChartRankingGraphDisplayMode.Position:
this.collectionCompleteSorted = items.OrderBy(i => i.Price).ThenBy(j => j.CurrentRanking).ToList();
break;
case CRSChartRankingGraphDisplayMode.Grade:
this.collectionCompleteSorted = items.OrderBy(i => i.TotalGrade).ThenBy(j => j.CurrentRanking).ToList();
break;
...
//default: // maybe you want this, too
}
答案 3 :(得分:1)
var q = collection.Where(co => !co.IsVirtual);
if (CurrentDisplayMode == CRSChartRankingGraphDisplayMode.Position)
{
q = q.OrderBy(co => co.Price).ThenBy(co => co.CurrentRanking);
}
else if (CurrentDisplayMode == CRSChartRankingGraphDisplayMode.Grade)
{
q = q.OrderBy(co => co.Rating.TotalGrade).ThenBy(co => co.CurrentRanking);
}
this.collectionCompleteSorted = q.ToList();