你可以使用这样的东西:
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);
但我怀疑第二个版本是个好主意。它使代码难以理解。我纯粹出于学术原因添加它,以展示什么是可能的。