45

我有一个带有日期时间字段的表。我想检索按月/年组合以及该月/年中出现的记录数分组的结果集。如何在 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)

但我不会说这有效...

4

5 回答 5

79
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 函数的列表。为此,您还需要了解多列分组

降序排列

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);
于 2009-04-18T04:58:21.607 回答
26

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

Assuming that you already have a collection of entities and each entity has OrderDate as one of its properties.

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();

If you do not need the collection of SelectListItem then just replace the select with this one:

.Select(x => string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count()))
于 2015-04-03T01:50:13.557 回答
7

你也可以这样做

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

你的结果将是

{2014 年 1 月 25 日} {2015 年 2 月 15 日} 等等...

于 2014-11-18T15:07:25.523 回答
1

本网站有一个可以满足您需求的示例。

这是基本语法:

from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
于 2009-04-18T04:41:01.853 回答
0

Here is a simple solution for grouping in 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();
于 2017-07-11T13:28:43.747 回答