【问题标题】:Linq: Totals Groups By MonthLinq:按月汇总组
【发布时间】:2012-01-03 22:20:21
【问题描述】:

我有一个简单的业务对象:

Crime 
     Date
     PersonsInvolved

我需要一份每月总参与人数的列表。数据为 1 年,因此无需考虑年份。

Jan 5
Feb 3
Mar 5

等等

如果我有这样的内存集合,在 Linq 中如何完成:

List<Crime>() crimes;

【问题讨论】:

    标签: c# linq group-by


    【解决方案1】:
    crimes.GroupBy(c => c.Date.Month)
          .Select(g => new { Month = g.Key, Count = g.Count() });
    

    【讨论】:

      【解决方案2】:
      var q = from i in crimes group i by i.Date.ToString("MMM") into grp select new {Month = grp.Key, Count = grp.Sum(i => i.Persons)};

      【讨论】:

        【解决方案3】:
        List<Crime>() crimes = ...
        var crimesPerMonth = crimes.GroupBy(x => x.Date.Month);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-03
          • 1970-01-01
          • 2021-02-16
          • 2021-05-05
          • 1970-01-01
          • 1970-01-01
          • 2022-11-22
          • 2016-07-19
          相关资源
          最近更新 更多