LINQ:在日期时间字段中按月份和年份分组 [英] LINQ: Group by month and year within a datetime field

查看:26
本文介绍了LINQ:在日期时间字段中按月份和年份分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期时间字段的表格.我想检索按月/年组合和该月/年中出现的记录数分组的结果集.这如何在 LINQ 中完成?

I have a table with a datetime field. I want to retrieve a result set grouped by the month/year combination and the number of records that appear within that month/year. How can this be done in LINQ?

我能找到的最接近的是 TSQL:

The closest I've been able to figure out is in TSQL:

select substring(mo,charindex(mo,'/'),50) from (
select mo=convert(varchar(2),month(created)) + '/' + convert(varchar(4), year(created)) 
 ,qty=count(convert(varchar(2),month(created)) + '/' + convert(varchar(4), year(created)))
from posts 
group by convert(varchar(2),month(created)) + '/' + convert(varchar(4), year(created))
) a
order by substring(mo,charindex(mo,'/')+1,50)

但我不会说那行得通...

But I wouldn't say that works...

推荐答案

var grouped = from p in posts
     group p by new { month = p.Create.Month,year= p.Create.Year } into d
     select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count() };

这是 LINQ 中可用的 DateTime 函数列表.为此,您还需要了解 多列分组

Here's the list of DateTime functions available in LINQ. For this to work you'll also need to understand multi-column grouping

降序排列

var grouped = (from p in posts 
  group p by new { month = p.Create.Month,year= p.Create.Year } into d 
  select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count()}).OrderByDescending (g => g.dt);

这篇关于LINQ:在日期时间字段中按月份和年份分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆