我有一个带有日期时间字段的表。我想检索按月/年组合以及该月/年中出现的记录数分组的结果集。这如何在 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)
但我不会说这有效......
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 中可用的日期时间函数列表。为此,您还需要了解多列分组
降序排列
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);
这适用于那些尝试使用 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()))
你也可以这样做
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 日}等...
此网站有一个示例可以满足您的需求。
这是基本语法:
from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
这是一个在日期时间中分组的简单解决方案。
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();
一种方法是下面的查询,其中查询按年份和月份对帖子进行分组,然后计算每组中的帖子数量。然后结果按年份和月份排序:
var query =
from post in posts
group post by new { post.Year, post.Month } into g
select new { g.Key.Year, g.Key.Month, Count = g.Count() };
以下是查询输出的示例:
[
{ Year: 2023, Month: 5, Count: 100 },
{ Year: 2023, Month: 6, Count: 201 },
{ Year: 2023, Month: 7, Count: 30 },
]