简体   繁体   English

在LINQ C#中按日期分组

[英]GroupBy Date in LINQ C#

I am trying to GROUPBY Date in a LINQ Query and display the output as shown below 我正在尝试在LINQ查询中使用GROUPBY Date并显示如下所示的输出

startdates: [

startdate: “4/1/2014”,

users: [

{userId, …},
{userId, …}

],

startdate: “4/2/2014”, users: [

{userId, …}
],
 …

]

The code is shown below 代码如下所示

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

Even though the Users are Grouped by StartDate, the output contains the startDate multiple times the same number of times as the number of Users.The output is shown below. 即使将用户按StartDate分组,输出也会包含多次与用户数量相同次数的startDate。输出如下所示。 I tried putting .Distinct() but it still repeats the startdate. 我尝试放置.Distinct(),但它仍然重复开始日期。 Can someone please help? 有人可以帮忙吗?

[{"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"}]

The problem is your selection part, here: 问题是您的选择部分,在这里:

.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})})});

You've got far too much nesting there. 您在那里嵌套太多了。 You're creating a startdate part for each element within the group. 你要创建一个startdate为组内的每个元素的一部分。

It's unclear why you're using grouping by three separate parts at all, but I suspect this will do what you want: 目前尚不清楚为什么要使用按三个独立部分进行分组,但是我怀疑这会满足您的要求:

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

If you need to wrap that in a startdates field, you can then use: 如果需要将其包装在startdates字段中,则可以使用:

var result = new { startdates = query.ToArray() };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM