具有条件聚合的Viewmodel(Sums)

时间:2017-05-11 04:02:03

标签: asp.net-mvc linq c#-4.0

我有一个viewmodel

public class RecTotal
{
    public string PayType { get; set; }

    public decimal TotalPrice { get; set; }

    public string Category { get; set; }
}

public class ReconcileViewModel
{
    public IEnumerable<RecTotal> RecTotals { get; set; }

    public IEnumerable<RecInvoiceLineItem> LineItems { get; set; }
}

如何创建类别的总和并为每个类别创建新的RecTotal记录。例如:

ReconcileViewModel VM = new ReconcileViewModel();

foreach(POSItemCategory cat in db.POSItemCategories)
            {
                recLineItems.Where(p => p.Category == cat.ID).Sum(p => p.InvPrice);
            }

我正在寻找的最终结果是

VM.RecTotal.Add(Sum(TotalPrice),foreach(Category)

我知道我很接近,但我不能理解它。

2 个答案:

答案 0 :(得分:0)

我找到了一种方法来做到这一点,但在我看来它是“丑陋的”,并且必须有更好的方法来做到这一点....

var test = new List<RecTotal>();
            foreach (POSItemCategory cat in db.POSItemCategories)
            {
                test.Add(new RecTotal
                {
                    NumberOfItems = recLineItems.Where(p => p.Category == cat.ID).Count(),
                    TotalPrice = recLineItems.Where(p => p.Category == cat.ID).Sum(p => p.InvPrice),
                    PayType = "All",
                    Category = cat.Name,
                    NumberOfInvoices = recLineItems.Where(p => p.Category == cat.ID).Select(p => p.InvID).Distinct().Count()
                });
            };
            VM.RecTotals = test;

如果有更好的方法,请告诉我。

答案 1 :(得分:0)

你可以试试这个

   var testdata = new List<RecTotal>();

   testdata = recLineItems.Where(x => db.POSItemCategories.Select(a=>a.ID).Contains(x.Category))
                        .GroupBy(x => x.Category)
                        .Select(
                            x =>
                                new RecTotal()
                                {
                                    Category = x.Key,
                                    PayType = "All",
                                    TotalPrice = x.Sum(z => z.InvPrice),
                                    NumberOfItems = x.Count(),
                                    NumberOfInvoices = x.Select(p => p.InvID).Distinct().Count()
                                }).ToList();