Daoming Yang
Daoming Yang

Reputation: 1325

How to use Linq group a order list by Date

I have a order list and want to group them by the created date.

Each order's created datetime will be like "2010-03-13 11:17:16.000"

How can I make them only group by date like "2010-03-13"?

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

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

Update: How can I group order by month? And the following code is not correct.

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

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

Many thanks.

Upvotes: 3

Views: 2136

Answers (3)

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

Use t => t.DateCreate.Date.

Upvotes: 0

Greg Beech
Greg Beech

Reputation: 136627

Using the .Date will discard the time component, e.g.

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

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532465

Use the Date property.

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

Upvotes: 2

Related Questions