在 ObservableCollection 上使用 LINQ with GroupBy 和 Sum 聚合



我有以下代码块可以正常工作;

var boughtItemsToday = (from DBControl.MoneySpent
            bought in BoughtItemDB.BoughtItems
            select bought);
BoughtItems = new ObservableCollection<DBControl.MoneySpent>(boughtItemsToday);

它从我的MoneySpend表中返回数据,其中包括ItemCategory,ItemAmount,ItemDateTime。

我想将其更改为按项目类别和项目金额分组,以便我可以看到我大部分钱花在哪里,所以我创建了一个 GroupBy 查询,并最终得到了这个;

var finalQuery = boughtItemsToday.AsQueryable().GroupBy(category => category.ItemCategory); 
BoughtItems = new ObservableCollection<DBControl.MoneySpent>(finalQuery);

这给了我 2 个错误;

错误 1 "System.Collections.ObjectModel.ObservableCollection.ObservableCollection(System.Collections.Generic.List)"的最佳重载方法匹配有一些无效参数

错误 2 参数 1:无法从"System.Linq.IQueryable>"转换为"System.Collections.Generic.List"

这就是我卡住的地方! 如何使用 GroupBy 和 Sum 聚合函数在 1 个 LINQ 查询中获取我的类别和关联支出的列表?!

任何帮助/建议都非常感谢。

马克

.GroupBy(category => category.ItemCategory);返回一个可枚举的 IGrouping 对象,其中每个 IGrouping 的键是一个不同的 ItemCategory 值,该值是 MoneySpent 对象的列表。 因此,您将无法像当前那样简单地将这些分组放入可观察集合中。

相反,您可能希望将每个分组结果选择到新的 MoneySpent 对象中:

var finalQuery = boughtItemsToday
    .GroupBy(category => category.ItemCategory)
    .Select(grouping => new MoneySpent { ItemCategory = grouping.Key, ItemAmount = grouping.Sum(moneySpent => moneySpent.ItemAmount);
BoughtItems = new ObservableCollection<DBControl.MoneySpent>(finalQuery);

您可以使用所需的属性将每个组投影到一个同名(或者更好的是为此创建新类型)类:

var finalQuery = boughtItemsToday.GroupBy(category => category.ItemCategory);
                                 .Select(g => new 
                                  { 
                                     ItemCategory = g.Key, 
                                     Cost = g.Sum(x => x.ItemAmount)
                                  });

根本不需要AsQueryable(),因为无论如何boughtItemsToday都是IQuerable。您也可以只组合查询:

var finalQuery = BoughtItemDB.BoughtItems
                             .GroupBy(item => item.ItemCategory);
                             .Select(g => new 
                              { 
                                  ItemCategory = g.Key, 
                                  Cost = g.Sum(x => x.ItemAmount)
                              });

最新更新