在 LINQ C# 中按日期分组
本文关键字:日期 LINQ | 更新日期: 2023-09-27 17:57:10
>我正在尝试在 LINQ 查询中按日期分组并显示如下所示的输出
startdates: [
startdate: “4/1/2014”,
users: [
{userId, …},
{userId, …}
],
startdate: “4/2/2014”, users: [
{userId, …}
],
…
]
代码如下所示
db.Users
.Where(x => (x.startDate >= startDate) && (x.startDate <= endDate))
.GroupBy(x => new { x.startDate.Day, x.startDate.Month, x.startDate.Year })
.ToList()
.Select(y => new
{
startdates = y.Select(k =>
new {startdate = (k.startDate.Month.ToString() + "/" + k.startDate.Day.ToString() + "/" + k.startDate.Year.ToString()),
users = y.Select(z =>
new {userId = z.userId,
userName = z.userName})})});
即使"用户"按"开始日期"分组,输出包含的"开始日期"的次数也是"用户数"的多次。输出如下所示。我试着把.Distinct() 但它仍然重复开始日期。有人可以帮忙吗?
[{"startdates":
[{"startdate":"04/01/2014",
"users":[
{"userId":1},"userName":"John"}
{"userId":2},"userName":"Mike"}],
[{"startdate":"04/01/2014",
"users":[
{"userId":1},"userName":"John"}
{"userId":2},"userName":"Mike"}],
[{"startdate":"04/02/2014",
"users":[
{"userId":3},"userName":"AL"}
{"userId":4},"userName":"Test"}],
[{"startdate":"04/02/2014",
"users":[
{"userId":3},"userName":"AL"}
{"userId":4},"userName":"Test"}]
问题是你的选择部分,在这里:
.Select(y => new
{
startdates = y.Select(k =>
new {startdate = (k.startDate.Month.ToString() + "/" + k.startDate.Day.ToString() + "/" + k.startDate.Year.ToString()),
users = y.Select(z =>
new {userId = z.userId,
userName = z.userName})})});
你在那里筑巢太多了。您正在为组中的每个元素创建一个startdate
部件。
目前还不清楚您为什么要按三个单独的部分进行分组,但我怀疑这会满足您的需求:
db.Users
.Where(x => (x.startDate >= startDate) && (x.startDate <= endDate))
.GroupBy(x => x.startDate.Date) // Or just x.startDate
.AsEnumerable() // Do the rest of the query locally
.Select(group => new
{
startdate = group.Key.ToString("MM/dd/yyyy"),
users = group.Select(z => new { z.userId, z.userName })
});
如果需要将其包装在startdates
字段中,则可以使用:
var result = new { startdates = query.ToArray() };