Search code examples
c#asp.net-mvclinqasp.net-coreasp.net-mvc-viewmodel

Loading LINQ results into a ViewModel that has a calculated attribute (column)


I've seen the scenarios where a ViewModel is populated with one LINQ query as shown below. Question: How can I populate the TotalSale attribute (column) - that is a grand total of Sale column - of the following ViewModel? Note: I'm using latest version of ASP.NET Core with VS2015.

ViewModel:

public class CategProdViewModel
{
    public string Category { get; set; }
    public string ProductName { get; set; }
    public float Sale { get; set; }
    public float TotalSale { get; set; }
}

Controller:

var innerJoinQuery =  from category in categories
       join prod in products on category.ID equals prod.CategoryID
       select new CategProdViewModel { Category = category.Name, ProductName = prod.Name, Sale = prod.Sale }; 

Solution

  • You don't clarify the structure of Product, but you can Sum multiple values

    var innerJoinQuery =  from category in categories
           join prod in products on category.ID equals prod.CategoryID
           select new CategProdViewModel { 
               Category = category.Name, 
               ProductName = prod.Name, 
               Sale = prod.Sale, 
               TotalSales = products.Sum(t => t.Sale) 
    };
    

    Without more about the code, it's hard to say, and also, the prod.sale is probably only going to be the amount of the last product. You can use Sum(this IEnumerable<TSource> source, Func<TSource, double> selector) to sum the total of multiple items.

    This is a quick answer. It will probably need to be altered depending on what the rest of your code looks like. You can also Group the query results to sum.