我发现自己在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();
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.
这就是我想要做的事情:
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();
Run Code Online (Sandbox Code Playgroud)
价格是我在rundate之后计算的价格.我可以以某种方式访问它吗?
您可以先选择匿名类型来存储该值:
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();
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用“真实”代码:
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();
Run Code Online (Sandbox Code Playgroud)