简体   繁体   English

选择中的Linq值之和

[英]Sums of Linq values in select

So I have always came across this situation when using linq. 因此,使用linq时,我总是遇到这种情况。 Say I have code like below: 说我有如下代码:

            var results = _context.Products.Select(d =>
            new Models.ProductData()
            {
                Id = d.ProductId,
                Name = d.Product.Name,
                Qty = d.Number.Where(y => y.Active && y.CodeId == 5 && y.Status == "NEW").Sum(y => y.FeeAmount),
                Qty1= d.Number.Where(y => y.Active && y.CodeId == 7 && y.Status == "NEW").Sum(y => y.Fee),
                Total = d.Number.Where(y => y.Active && y.CodeId == 5 && y.Status == "NEW").Sum(y => y.FeeAmount) + d.Number.Where(y => y.Active && y.CodeId == 7 && y.Status == "NEW").Sum(y => y.Fee)
            }
            );

For the total value, is there a better way to calculate the total without having to write out all the linq statements with + symbols in between? 对于合计值,是否有更好的方法来计算合计,而不必写出所有linq语句,且两者之间带有+符号? It would be a lot nicer to be able to write something like 能够写类似这样的东西会更好

Total = Qty + Qty1

I could omit the total from the initial mapping and the remap it grouping by Id and assigning the totals there by referencing Total = Qty + Qty1 but that just seems to round about. 我可以省略初始映射中的总数,并通过ID将其重新映射分组,然后通过引用Total = Qty + Qty1在那里分配总数,但这似乎可以解决。

Any suggestions are appreciated. 任何建议表示赞赏。

In your Models.ProductData class, define the Total property as follows: 在您的Models.ProductData类中,如下定义Total属性:

public double Total {
    get {
        return this.Qty + this.Qty1;
    }
}

and avoid to set it in the Linq query. 并避免在Linq查询中进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM