如何在 LINQ 中执行此公式
本文关键字:执行 LINQ | 更新日期: 2023-09-27 17:57:02
我的公式如下所示:
Conversion = Settled / (Settled + Cancelled)
如何在 LINQ 语句中执行此操作?
这是我的代码:
WIP = g.Where(v => v.StatusCategoryID == 40).Sum(c => c.Amount) ?? 0,
Settled = g.Where(v => v.StatusCategoryID == 11).Sum(c => c.Amount) ?? 0,
Cancelled = g.Where(v => v.StatusCategoryID == 10).Sum(c => c.Amount) ?? 0,
你可以
用Aggregate
尝试这样的事情(虽然感觉有点虐待):
var agg = g.Aggregate(new { wip = 0, settled = 0, cancelled = 0 }, (a, curr) =>
{
return new
{
wip = a.wip + a.StatusCategoryID == 40 ? curr.Amount : 0,
settled = a.settled + a.StatusCategoryID == 11? curr.Amount : 0,
cancelled = a.cancelled + a.StatusCategoryID == 10? curr.Amount : 0,
};
});
然后你可以:
var Conversion = agg.settled / (agg.settled + agg.cancelled);
和:
var WIP = agg.wip;
这样做的好处是,您只需在一次循环中对所有三个类别求和。我不确定我是否发现这比仅使用 foreach
循环要好得多。