Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list by distinct date

Tags:

c#

linq

Another easy one hopefully.

Let's say I have a collection like this:

List<DateTime> allDates;

I want to turn that into

List<List<DateTime>> dividedDates;

where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.

Is there a bit of LINQ trickery that my tired mind can't pick out right now?

Solution

The Accepted Answer is correct.

Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax. And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-)

like image 422
Matt Mitchell Avatar asked Sep 16 '08 06:09

Matt Mitchell


2 Answers

var q  = from date in allDates 
         group date by date.Year into datesByYear
         select datesByYear.ToList();
q.ToList(); //returns List<List<DateTime>>
like image 197
Mark Cidade Avatar answered Nov 10 '22 05:11

Mark Cidade


Here's the methods form.

allDates
  .GroupBy(d => d.Year)
  .Select(g => g.ToList())
  .ToList();
like image 33
Amy B Avatar answered Nov 10 '22 05:11

Amy B