你可以使用這樣的事情:
var fees = from fee in schoolFeesResult
let weight = fee.Amount.Value/totalFees
select new
{
TuitionFee = weight * fee.TuitionFee.Value,
TravellingFee = weight * fee.TravellingFee.Value,
ResidentialFee = weight * fee.ResidentialFee.Value
};
// if the calculation of the fees is a performance bottleneck,
// uncomment the next line:
// fees = fees.ToList();
return new SchoolFees(
new Percentage(fees.Sum(x => x.TuitionFee),
new Percentage(fees.Sum(x => x.TravellingFee),
new Percentage(fees.Sum(x => x.ResidentialFee));
你甚至能走得更遠:
var fees = (from fee in schoolFeesResult
let weight = fee.Amount.Value/totalFees
group fee by 1 into g
select new
{
TuitionFee = g.Sum(x => weight * x.TuitionFee.Value),
TravellingFee = g.Sum(x => weight * x.TravellingFee.Value),
ResidentialFee = g.Sum(x => weight * x.ResidentialFee.Value)
}).Single();
return new SchoolFees(
new Percentage(fees.TuitionFee,
new Percentage(fees.TravellingFee,
new Percentage(fees.ResidentialFee);
但我懷疑,這第二個版本是一個好主意。它使代碼難以理解。我純粹出於學術原因添加了它,以展示什麼是可能的。
+1:很好,我喜歡它。注意:這也將枚舉'schoolFeesResult'三次。 –
@DanielHilgarth謝謝!是的,它枚舉了三次,但它不錯:)順便說一句,沒有什麼區別 - 枚舉三次(原始代碼),但我不計算每個'重量*費用':) –
它會計算每個重量(' x.Amount.Value/totalFees')三次,就像原始代碼一樣。就像原始代碼一樣,它只會計算每個單獨的「重量*費用」。所以,就計算而言,它是一樣的。只是更多的風格:) –