LINQ:在datetime字段中按月和年分组

时间:2009-04-18 04:35:42

标签: linq tsql group-by substring

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

我能够弄清楚的最接近的是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)

但我不会说有效......

5 个答案:

答案 0 :(得分:66)

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函数列表。为此,您还需要了解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);

答案 1 :(得分:12)

这适用于那些试图完成同样但使用lambda表达式的人。

假设您已经拥有一组实体,并且每个实体都将OrderDate作为其属性之一。

yourCollection
// This will return the list with the most recent date first.
.OrderByDescending(x => x.OrderDate)
.GroupBy(x => new {x.OrderDate.Year, x.OrderDate.Month})
// Bonus: You can use this on a drop down
.Select(x => new SelectListItem
        {
           Value = string.Format("{0}|{1}", x.Key.Year, x.Key.Month),
           Text = string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count())
        })
.ToList();

如果您不需要SelectListItem的集合,那么只需将select替换为:

.Select(x => string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count()))

答案 2 :(得分:3)

你也可以这样做

from o in yg
group o by o.OrderDate.ToString("MMM yyyy") into mg
select new { Month = mg.Key, Orders = mg }

您的结果将是

{Jan 2014,25} {Feb 2015,15}等......

答案 3 :(得分:1)

This Site有一个例子可以满足您的需求。

这是基本语法:

from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }

答案 4 :(得分:0)

以下是在DateTime中进行分组的简单解决方案。

List<leaveallview> lav = new List<leaveallview>();
lav = dbEntity.leaveallviews.Where(m =>m.created==alldate).ToList();
dynamic lav1 = lav.GroupBy(m=>m.created.Value.GetDateTimeFormats()).FirstOrDefault().ToList();