Matthias
Matthias

Reputation: 928

Selecting the newest entry of each day

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

Answers (2)

Abdellah OUMGHAR
Abdellah OUMGHAR

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

Yacoub Massad
Yacoub Massad

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

Related Questions