【问题标题】:Multiply two fields in Linq在 Linq 中将两个字段相乘
【发布时间】:2017-12-25 22:43:03
【问题描述】:

在 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,
}

如果不是,请给出任何正确的代码

【问题讨论】:

  • 你只做对了。有什么问题?
  • 在乘法之前检查 null 或 0 值。比如 total = (x.qty != 0 ? x.qty : 1) *(x.unitprice != 0 ? x.unitprice : 1)

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


【解决方案1】:

您可以考虑在 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
             };

【讨论】:

    【解决方案2】:

    你可能想要一个Select() 子句:

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

    但看起来你需要一个像这样的 get only 属性:

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

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2010-12-24
      相关资源
      最近更新 更多