将两个lambda表达式的值相乘

时间:2016-07-05 09:24:10

标签: c# linq lambda

此代码将第1个月的音量乘以增长因子:

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; }
}

1 个答案:

答案 0 :(得分:1)

没有神奇的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();