如何使用Linq组按日期排列的订单列表

问题描述:

我有一个订单列表,并希望按创建日期对它们进行分组。如何使用Linq组按日期排列的订单列表

每个订单的创建日期时间就会像“2010-03-13 11:17:16.000”

我怎样才能让他们只能按日期如“2010-03-13”?

var items = orderList.GroupBy(t => t.DateCreated) 
.Select(g => new Order() 
{ 
    DateCreated = g.Key 

}) 
.OrderByDescending(x => x.OrderID).ToList(); 

更新:如何按月对订单进行分组?以下代码不正确。

var items = orderList.GroupBy(t => t.DateCreated.Month) 
.Select(g => new Order() 
{ 
    DateCreated = g.Key 

}) 
.OrderByDescending(x => x.OrderID).ToList(); 

非常感谢。

+0

你终于找到了如何做到这一点只与年份? – oCcSking 2013-07-15 08:54:40

使用Date属性。

var items = orderList.GroupBy(t => t.DateCreated.Date) 

使用.Date将丢弃时间分量,例如,

var items = orderList.GroupBy(t => t.DateCreated.Date) 

使用t => t.DateCreate.Date