2017-07-20 23 views
-2

领域是否有LINQ乘两个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, 
} 

如果不是请放弃任何合适的代码

+1

你做的唯一正确的。有什么问题? –

+0

乘数前检查空值或0值。如** total =(x.qty!= 0?x.qty:1)*(x.unitprice!= 0?x.unitprice:1)** –

回答

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; 
} 
3

你可以考虑使用let关键字在LINQ查询语法

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