2013-07-04 27 views
1

我想LINQ到组通过日期,但显示在文本LINQ组通过,然后显示(DD MMM)

这里的日期时间是我的代码

var groups = _uow.Orders.GetAll() 
      .Where(x => x.Created > baselineDate) 
      .GroupBy(x => x.Created.ToString("yyyy-MM-dd")); 

var orders = new 
     { 
      Day = groups.Select(g => g.Key).ToArray(), 
      Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(), 
     }; 

结果(不好放在图表的标签)

{"Day": [2, 3, 4, 5], "Total": [9999.00, 9999.00, 9999.00, 9999.00] } 

但我想这(每月)

"Day": ['Jan', Feb', 'Mar', 'Apr'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] } 

或每日

"Day": ['Jan 1', 'Jan 2', 'Jan 3', 'Jan 4'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] } 

请咨询我则DateTime.ToString(),我可以玩。

谢谢大家。

回答

2

This question描述如何将日期时间转换为月份的字符串名称。

编辑:为EF,我们做任何字符串逻辑之前拉一切到内存:

var orders = _uow.Orders.GetAll() 
    .Where(x => x.Created > baselineDate) 
    // pull into memory here, since we won't be making the result set any smaller and 
    // we want to use DateTime.ToString(), which EF won't compile to SQL 
    .AsEnumerable() 
    // this will group by the whole date. If you only want to group by part of the date, 
    // (e. g. day or day, month), you could group by x => x.Date.Month or the like 
    .GroupBy(x => x.Date) 
    .Select(g => new { 
     // or use just "MMM" for just the month 
     Dates = g.Select(g => g.Key.ToString("MMM d")).ToArray(), 
     Total = ... 
    }); 
+1

这应该是一个评论 –

+0

是啊,我知道如何使用的ToString( “MMMM”)或任何别人stringFormat。但是当我使用LINQ进行分组时,它不起作用。 – riseres

+0

@riseres是否将linq用于对象? Linq to SQL? EF? NHibernate的? – ChaseMedallion

0

您需要使用的功能是EF能够理解并转化为SQL,如EntityFunctions.TruncateTime。这是您更新的代码:

var groups = _uow.Orders.GetAll() 
      .Where(x => x.Created > baselineDate) 
      .GroupBy(x => EntityFunctions.TruncateTime(x.Created)); 

然后使用字符串格式化只是在输出中,但要确保你价值已恢复到.NET之后做,使用AsEnumerable切换到Linq- to-Objects:

var orders = new 
     { 
      Day = groups.Select(g => g.Key) 
         .AsEnumerable() 
         .Select(x => x.ToString("MMM d")) 
         .ToArray(), 
      Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(), 
     }; 
2

谢谢大家的帮助。 我找到了答案。

添加

.AsEnumerable() 

.GroupBy(x => x.Created.ToString("MMM d")); 

这里是完整的代码

var groups = _uow.Orders.GetAll() 
      .Where(x => x.Created > baselineDate) 
      .AsEnumerable() 
      .GroupBy(x => x.Created.ToString("MMM d")); 

     var orders = new 
     { 
      Day = groups.Select(g => g.Key).ToArray(), 
      Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(), 
     };