我的课程如下。
public class ModelMMaster
{
public string OrderID { get; set; }
public bool IsActive { get; set; }
public List<ModelDetail> _detail { get; set; }
}
public class ModelDetail
{
public string SKUCode { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
}
我有一个订单列表
List<ModelMMaster> _listMaster = new List<ModelMMaster>
我想用LINQ计算Sum(Quantity * Price)
上的_listMaster
。
我对此感到困惑。
double _sum =_listMaster.Where(f => f.IsActive == true).Select(f => f._detail)......
如何使用LINQ从_listMaster计算总和(数量*价格)?
答案 0 :(得分:6)
您可以通过几种方式实现它
选项1
double _sum =_listMaster.Where(f => f.IsActive)
.Sum(x=>x._detail.Sum(c=>c.Price * c.Quantity));
选项2
double _sum =_listMaster.Where(f => f.IsActive)
.Aggregate(0d,(result,item)=>result + item._detail.Sum(x=>x.Price * x.Quantity));
选项3
double _sum =_listMaster.Where(f => f.IsActive)
.SelectMany(x=>x._detail)
.Sum(x=>x.Price * x.Quantity);
答案 1 :(得分:3)
List<ModelMMaster> _listMaster = new List<ModelMMaster>();
List<ModelDetail> _listDetail = new List<ModelDetail>();
_listDetail.Add(new ModelDetail { SKUCode = "SKUCode-1", Quantity = 1, Price = 1 });
_listMaster.Add(new ModelMMaster { OrderID = "OrderID-1", IsActive = true, _detail = _listDetail });
_listDetail = new List<ModelDetail>();
_listDetail.Add(new ModelDetail { SKUCode = "SKUCode-2", Quantity = 2, Price = 2 });
_listDetail.Add(new ModelDetail { SKUCode = "SKUCode-3", Quantity = 3, Price = 3 });
_listMaster.Add(new ModelMMaster { OrderID = "OrderID-2", IsActive = true, _detail = _listDetail });
var totalSum = _listMaster.Where(t=>t.IsActive).SelectMany(t => t._detail).Sum(t => t.Quantity * t.Price);