[英]LINQ Min() and Max() optimisation
我在做正確的方面遇到了一些麻煩。
我需要為列表中的列表中的列表選擇最小值和最大值
有沒有想過如何創建優化類型?
var range = allFilteredCars
.SelectMany(car => car.LeasingPlans
.SelectMany(plan => plan.Durations)
.Select(a => a.MonthlyPrice))
.ToList();
var min = range.Min();
var max = range.Max();
最后一個Min()
和Max()
感覺不對。
有什么想法嗎?
我只想通過在整個集合上迭代一次來計算min
和max
一種方法,這可以使用foreach
循環來完成
var min = Int32.MaxValue;
var max = Int32.MinValue;
foreach(var filteredCard in allFilteredCars)
{
foreach(var leasingPlan in filteredCard.LeasingPlans)
{
foreach(var car in leasingPlan.Durations)
{
if(car.MonthlyPrice < min)
min = car.MonthlyPrice;
else if(car.MonthlyPrice > max)
max = car.MonthlyPrice;
}
}
}
假設
MonthlyPrice
是Int
我們會做一件壞事 :帶有副作用的linq表達式。
int? min = null;
int? max = null;
allFilteredCars
.SelectMany(car => car.LeasingPlans
.SelectMany(plan => plan.Durations))
.Select(a =>
{
if (min == null || a.MonthlyPrice < min.Value)
{
min = a.MonthlyPrice;
}
if (max == null || a.MonthlyPrice > max.Value)
{
max = a.MonthlyPrice;
}
return true;
}).All(x => x);
最后你似乎不需要range
結果......你只需要Min()
和Max()
,所以我們計算它,並強制通過使用All()
來詳細闡述整個IEnumerable<>
All()
。
你必須替換int?
與MonthlyPrice
的類型!
我不認為你可以繞過多個SelectMany
但查詢中的Ordering將擺脫Min / Max。 這應該更快,因為你只排序一次:
var range = allFilteredCars
.SelectMany(car => car.LeasingPlans
.SelectMany(plan => plan.Durations)
.Select(a => a.MonthlyPrice))
.OrderBy(a => a))
.ToList();
var min = range[0]; // get the first
var max = range[range.Count-1]; // get the last
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.