Reputation: 137
My classes are like below.
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; }
}
And I have an order list like
List<ModelMMaster> _listMaster = new List<ModelMMaster>
I want to calculate Sum(Quantity * Price)
with LINQ, over _listMaster
.
I am stuck at this.
double _sum =_listMaster.Where(f => f.IsActive == true).Select(f => f._detail)......
How can i calculate Sum(Quantity * Price) from _listMaster with LINQ?
Upvotes: 2
Views: 1949
Reputation: 18155
You can achieve it couple of ways
Option 1
double _sum =_listMaster.Where(f => f.IsActive)
.Sum(x=>x._detail.Sum(c=>c.Price * c.Quantity));
Option 2
double _sum =_listMaster.Where(f => f.IsActive)
.Aggregate(0d,(result,item)=>result + item._detail.Sum(x=>x.Price * x.Quantity));
Option 3
double _sum =_listMaster.Where(f => f.IsActive)
.SelectMany(x=>x._detail)
.Sum(x=>x.Price * x.Quantity);
Upvotes: 8
Reputation: 1069
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);
Upvotes: 4