从 OData API 检索数据时如何进行 GroupBy?

How to GroupBy when retrieving data from OData API?

我正在从 OData API 检索数据并将其投影到不同的 class:

            data = context.Product.Where(p => p.name == name)
                                             .Take(10)
                                             .Select(p => new MyCustomProduct
                                             {
                                                 id = p.id,                                                 
                                                 year = p.year,
                                                 amount = p.amount,                                                 
                                                 customProperty = 00
                                             });

这很好用。但是,我还需要一个函数来按年份对检索到的产品进行分组,并计算每年的产品总量。如何实现?

首先按年份对结果进行分组,然后计算每年的总和:

var data = context.Product.Where(p => p.name == name)
                      .Take(10)
                      .GroupBy(p => p.year)
                      .Select(group => new { year = group.Key, sum = group.Sum(p => p.amount) })
                      .ToList();

你的数据变量是 List<a'> 其中 a' = { int year, int sum }