【问题标题】:Viewmodel with conditional aggregation (Sums)具有条件聚合的视图模型(总和)
【发布时间】:2017-05-11 04:02:03
【问题描述】:

我有一个视图模型

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; }
}

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

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)

我知道我已经很接近了,但我就是不明白。

【问题讨论】:

  • cat.ID 是字符串吗?类别名称?
  • 以下解决方案适合您吗?
  • 我已经使用了我的列表解决方案。我对您提出的解决方案有疑问,而不是解决问题,我只是使用了我的列表解决方案。不过谢谢你的建议
  • 我很难使用您提出的解决方案来弄清楚如何使 lambdas 为我的确切目的正常工作。

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


【解决方案1】:

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

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;

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

【讨论】:

    【解决方案2】:

    你可以试试这个

       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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 2021-06-29
      • 2022-01-07
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多