Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Split list into lists by date [closed]

Tags:

c#

list

linq

I have list of objects List<Payment>. I would like to get list of lists grouped by PaymentDate. Something like that: List<List<Payments>> where each list of the list have same date (without hours).

like image 466
Ellbar Avatar asked Nov 30 '22 20:11

Ellbar


2 Answers

DateTime has a Date property:

List<List<Payments>> result = payments 
    .GroupBy(p => p.PaymentDate.Date)
    .Select(g => g.ToList())
    .ToList();
like image 58
Tim Schmelter Avatar answered Dec 09 '22 13:12

Tim Schmelter


You can either use GroupBy as suggested by others, or you can just create a Lookup:

var lookup = payments.ToLookup(payment => payment.PaymentDate.Date);

You can iterate over that (using each group's key as the date) or fetch all the payments for a given date using the indexer. I usually find that a lookup is cleaner than using a nested collection such as a List<List<...>> or a Dictionary<..., List<...>>.

like image 43
Jon Skeet Avatar answered Dec 09 '22 13:12

Jon Skeet