c#linq扩展组,并按季度选择数据,其中缺少月份

c#linq扩展组,并按季度选择数据,其中缺少月份,c#,linq,extension-methods,C#,Linq,Extension Methods,我有包括日期和总数的数据。 我需要按季度计算销售额。 输出按季度返回销售总额数组, 结果[0]是第一季度的销售总额,结果是第二季度的销售总额等 例如,输入“sales”: /// {} => { 0, 0, 0, 0} /// {(1/1/2010, 10), (2/2/2010, 10), (3/3/2010, 10)} => { 30, 0, 0, 0 } /// {(1/1/2010, 10), (4/4/2010, 10), (10/10/2010, 10)} => {

我有包括日期和总数的数据。 我需要按季度计算销售额。 输出按季度返回销售总额数组, 结果[0]是第一季度的销售总额,结果是第二季度的销售总额等

例如,输入“sales”:

/// {} => { 0, 0, 0, 0}
/// {(1/1/2010, 10), (2/2/2010, 10), (3/3/2010, 10)} => { 30, 0, 0, 0 }
/// {(1/1/2010, 10), (4/4/2010, 10), (10/10/2010, 10)} => { 10, 10, 0, 10 }
我知道如何分组,但有一个丢失宿舍的问题

sales.GroupBy(item => ((item.Item1.Date.Month - 1) / 3))
     .Select(x => new { Quarter = x.Key, Sum = x.Sum(item => item.Item2) })

一个很好,但我无法针对我的情况管理它,因为您的数据不一定包含所有季度,您应该
将其加入到所有季度的集合中。要创建这样的值,请使用可枚举的.Range

var groupedSales = sales.GroupBy(item => ((item.Date.Month - 1) / 3))
                        .Select(x => new { Quarter = x.Key, 
                                           Sum = x.Sum(item => item.Amount) });

var result = (from quarter in Enumerable.Range(0, 4)
              join sale in groupedSales on quarter equals sale.Quarter into grouping
              from sale in grouping.DefaultIfEmpty()
              select new { Quarter = quarter, Sum = sale?.Sum ?? 0 }).ToList();
一些测试数据:

List<dynamic> sales = new List<dynamic>
{
   new { Date = new DateTime(2010,1,1), Amount = 10 },
   new { Date = new DateTime(2010,2,2), Amount = 10 },
   new { Date = new DateTime(2010,3,3), Amount = 10 },
   new { Date = new DateTime(2010,4,4), Amount = 10 },
   new { Date = new DateTime(2010,5,5), Amount = 10 },
   new { Date = new DateTime(2010,6,6), Amount = 10 },
};
List sales=新列表
{
新{Date=new DateTime(2010,1,1),Amount=10},
新{Date=new DateTime(2010,2,2),Amount=10},
新{日期=新日期时间(2010,3,3),金额=10},
新{日期=新日期时间(2010,4,4),金额=10},
新{日期=新日期时间(2010,5,5),金额=10},
新{日期=新日期时间(2010,6,6),金额=10},
};

非常感谢。它起作用了。如何借助扩展方法编写此linq?p、 我试过Join、Union、GroupJoin,但找不到扩展方法的正确解决方案,这对我更好地理解它的工作原理很重要。@iiyalabachuski-我想你是说使用linq的方法语法而不是查询语法-检查我给你的左Join链接。其中一个示例使用syntaxyep方法。我只是瞥了一眼,把它标在书签上,以便以后再看。在链接中是一切。太多了!这个答案假设日期在一年之内。“有什么办法可以让它持续多年吗?”SomaMbadiwe-group在当年和当年都是如此。看看使用linq按多个值分组