// GET: Profit public ActionResult Index() { List <PL> pls = new List <PL>(); // get realised profit var profits = db.Profits.Include(p => p.Stock); foreach (Profit p in profits) { PL pl = new PL(); pl.Stock = p.Stock; pl.RealisedAmount = p.Amount * ExchangeRateService.GetRate(p.Stock.Currency); pls.Add(pl); } // get unrealised profit var portfolios = db.Portfolios.Include(p => p.Stock); foreach (Portfolio p in portfolios) { PL pl = pls.Where(item => item.Stock.ID == p.StockID).FirstOrDefault(); if (pl == null) { pl = new PL(); pl.Stock = p.Stock; pls.Add(pl); } pl.UnrealisedAmount = p.PL; } // add divident var dividents = db.Dividents.Include(p => p.Stock); foreach (Divident d in dividents) { PL pl = pls.Where(item => item.Stock.ID == d.StockID).FirstOrDefault(); if (pl == null) { pl = new PL(); pl.Stock = d.Stock; pls.Add(pl); } pl.RealisedAmount += d.AmountSGD; } // update total profit/loss foreach (PL pl in pls) { pl.Amount = pl.RealisedAmount + pl.UnrealisedAmount; } decimal totalAmountSGD = (from od in pls select od.Amount).Sum(); ViewBag.TotalAmountSGD = totalAmountSGD; return(View(pls)); }