Reputation: 928
Consider the simple class
public class Data
{
public DateTime Date;
public object Content;
}
Now I have a IEnumerable<Data>
called datas
and I want Linq to sort the older items of each day out. Such that if there are items of the same day, I am only interested in the latest item of that day.
Is this possible with Linq?
Upvotes: 3
Views: 66
Reputation: 3745
Use this :
var result = from x in datas
group x by x.Date.Date into g
select g.OrderByDescending(x => x.Date).FirstOrDefault();
Or
var result = datas.GroupBy(x => x.Date.Date)
.Select(g => g.Where(x => x.Date == g.Max(y => y.Date))
.First());
Upvotes: 2
Reputation: 27861
Here is how you can do it:
var result =
datas
//Group by day (we don't include time here)
.GroupBy(x => x.Date.Date)
//For each group (day), get most recent item (we include time here)
.Select(g => g.OrderByDescending(x => x.Date).First())
.ToList();
For more readability, you could also use x.TimeOfDay
instead of x.Date
in the Select
statement.
Upvotes: 4