下面的代码将第一个月的容量乘以一个增长因子:
forecastData.Where(c => c.Date == months.ElementAt(1)).Sum(c =>
(c.Volume * c.Growth))
我也希望能够在这个表达式中使用第6个月的增长值。我可以用x作为第6个月的值所以结果是:
.Sum(c => (c.Volume * c.Growth) * x.Growth)
这可能吗?
数据类:public class ForecastedVolumeMonthly
{
public int VolumeMonthlyId { get; set; }
// Location
public int DepartureDepoId { get; set; }
public virtual Depo DepartureDepo { get; set; }
// Destination
public int DestinationDepoId { get; set; }
public virtual Depo DestinationDepo { get; set; }
// Nationality
public int NationalityId { get; set; }
public virtual Country Nationality { get; set; }
public long? Volume { get; set; }
public double? Growth { get; set; }
public DateTime Date { get; set; }
}
没有神奇的Linq语法可以做到这一点,但它非常简单。如果只有一个值,在循环外计算它(Linq Extension):
(注意将months.ElementAt(1)
移出循环会更好地提高性能)
DateTime monthParam = months.ElementAt(1);
double? growth = forecastData.Where(x => x.Date.Month == 6)
.Select(x => x.Growth).FirstOrDefault();
double? sum = forecastData.Where(c => c.Date == monthParam)
.Sum(c =>(c.Volume * c.Growth) * growth);
编辑后注释:
double? sum1 = (from c in forecastData
where c.Date == monthParam
let month6Val = forecastData.FirstOrDefault
(x => x.DepartureDepo = c.DepartureDepo
&& x.DestinationDepo = c.DestinationDepo)?.Growth
select c.Volume * c.Growth * month6Val).Sum();