在Linq中乘以两个字段

时间:2017-07-20 09:51:18

标签: asp.net-mvc entity-framework linq linq-to-entities

在LINQ

中有两个字段相乘的选项吗?
public class details
{
 public int qty { get; set; }
 public decimal unitprice{ get; set; }
 public decimal total{ get; set; }
}

select new details
{
 qty =x.qty ,
 unitprice= x.unitprice,
 total= x.qty*x.unitprice,
}

如果没有请给出任何正确的代码

2 个答案:

答案 0 :(得分:3)

您可能需要Select()子句:

someLinqQuery.Select(detailsObject => new details
{
    qty = detailsObject.qty,
    unitprice = detailsObject.unitprice,
    total = detailsObject.qty * detailsObject.unitprice
}

但看起来你需要一个这样的获取属性:

public class details
{
    public int qty { get; set; }
    public decimal unitprice { get; set; }
    public decimal total =>  qty * unitprice;
}

答案 1 :(得分:3)

您可以考虑在linq查询语法中使用let关键字

var result = from x in items
             let total = ((decimal)x.qty) * x.unitprice
             select new details {
                 qty = x.qty ,
                 unitprice = x.unitprice,
                 total = total
             };