我发现自己在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();其中价格是我在运行日期之后计算出来的价格。我能以某种方式访问这个吗?
发布于 2014-05-07 08:43:17
您可以首先选择一个匿名类型来存储此值:
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();另一种方法是使用“真实”代码:
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();发布于 2014-05-07 08:48:19
通过使用查询语法 (from),您可以使用让子句:
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();https://stackoverflow.com/questions/23512856
复制相似问题