使用已计算的元素

时间:2014-05-07 08:40:13

标签: c# linq

我发现自己在linq语句中重复计算,我想知道我是否可以某种方式访问​​已经计算过的元素。这就是我在做的事情:

var result = testdata.GroupBy(a => new { a.reportinggroup, a.commodity, a.timestep.Year })
                     .Select(g => new EndResult
                            {
                                rundate = rundate.ToShortDateString(),
                                price = g.Sum(a => (a.timestep.ispeak()) ? a.price : 0) / g.Sum(a => (a.timestep.ispeak()) ? 1 : 0),
                                valueposition = g.Sum(a => (a.timestep.ispeak()) ? a.position * a.price : 0) / (g.Sum(a => (a.timestep.ispeak()) ? a.price : 0) / g.Sum(a => (a.timestep.ispeak()) ? 1 : 0)),

                            }).ToList();

哪种方法正常。

这就是我想要做的事情:

var result = testdata.GroupBy(a => new { a.reportinggroup, a.commodity, a.timestep.Year })
                     .Select(g => new EndResult
                            {
                                rundate = rundate.ToShortDateString(),
                                price = g.Sum(a => (a.timestep.ispeak()) ? a.price : 0) / g.Sum(a => (a.timestep.ispeak()) ? 1 : 0),
                                valueposition = g.Sum(a => (a.timestep.ispeak()) ? a.position * a.price : 0) / price,           
                            }).ToList();

其中价格是我在rundate之后计算的价格。我可以以某种方式访问​​它吗?

2 个答案:

答案 0 :(得分:2)

您可以先选择匿名类型来存储此值:

result = testdata.GroupBy(a => new { a.reportinggroup, a.commodity, a.timestep.Year })
.Select(g => new { 
    rundate = rundate.ToShortDateString(), 
    price = g.Sum(a => (a.timestep.ispeak()) ? a.price : 0) / g.Sum(a => (a.timestep.ispeak()) ? 1 : 0),
    group = g
})
.Select(x => new EndResult
{
    rundate = x.rundate,
    price = x.price,
    valueposition = x.group.Sum(a => (a.timestep.ispeak()) ? a.position * x.price : 0) / x.price
}).ToList();

另一种方法是使用" real"代码:

result = testdata.GroupBy(a => new { a.reportinggroup, a.commodity, a.timestep.Year })
.Select(g => { 
    var price = g.Sum(a => (a.timestep.ispeak()) ? a.price : 0) / g.Sum(a => (a.timestep.ispeak()) ? 1 : 0);
    EndResult endRes = new EndResult { 
        rundate = rundate.ToShortDateString(),
        price = price,
        valueposition = x.group.Sum(a => (a.timestep.ispeak()) ? a.position * price : 0) / price)
    };
    return endRes;
}).ToList();

答案 1 :(得分:2)

使用query syntaxfrom),您可以使用let子句:

 var result = (from g in  testdata.GroupBy(a => new { a.reportinggroup, a.commodity, a.timestep.Year })
               let price = g.Sum(a => (a.timestep.ispeak()) ? a.price : 0) / g.Sum(a => (a.timestep.ispeak()) ? 1 : 0)
               select new EndResult
               {
                   rundate = rundate.ToShortDateString(),
                   price = price,
                   valueposition = g.Sum(a => (a.timestep.ispeak()) ? a.position * a.price : 0) / price,
                }).ToList();