[Solved] How to filter data based on maximum datetime value in each day [closed]


With data like:

public class Data
{
    public String Name
    {
        get;
        set;
    }

    public DateTime TimeStamp
    {
        get;
        set;
    }

    public Data(String name, DateTime timeStamp)
    {
        this.Name = name;
        this.TimeStamp = timeStamp;
    }

    public override string ToString()
    {
        return String.Format("{0} at {1}", this.Name, this.TimeStamp);
    }
}

You can use:

var source = new Data[]
{
    new Data("Yesterday early", DateTime.Today.AddDays(-1)),
    new Data("Yesterday middle", DateTime.Today.AddDays(-1).AddHours(2)),
    new Data("Yesterday middle", DateTime.Today.AddDays(-1).AddHours(2)),
    new Data("Yesterday late", DateTime.Today.AddDays(-1).AddHours(3)),

    new Data("Today early", DateTime.Today),
    new Data("Today middle", DateTime.Today.AddHours(2)),
    new Data("Today late 1", DateTime.Today.AddHours(3)),
    new Data("Today late 2", DateTime.Today.AddHours(3)),

    new Data("Tomorrow early", DateTime.Today.AddDays(1)),
    new Data("Tomorrow middle", DateTime.Today.AddDays(1).AddHours(2)),
    new Data("Tomorrow late 1", DateTime.Today.AddDays(1).AddHours(3)),
    new Data("Tomorrow late 2", DateTime.Today.AddDays(1).AddHours(3)),
};


var lateInDays = source.
    GroupBy((data) => data.TimeStamp.Date).
    Select(dayGroup =>
        new 
        {
            DayGroup = dayGroup, 
            MaxTimeInDay = dayGroup.Max(data => data.TimeStamp)
        }).
    SelectMany((dayGroupWithMaxTime) =>
        dayGroupWithMaxTime.
            DayGroup.
            Where(data =>
                (data.TimeStamp == dayGroupWithMaxTime.MaxTimeInDay)));

This is far from optimal, but it works.

How it works:

1. GroupBy((data) => data.TimeStamp.Date). – Groups your data items by their date( for three days there is three groups)

2. Part:

 Select(dayGroup =>
        new 
        {
            DayGroup = dayGroup, 
            MaxTimeInDay = dayGroup.Max(data => data.TimeStamp)
        }).

Augments each of three by-day groups with information about their maximal time in day(actually with full DateTime, so you may want to use DateTime.TimeOfDay property instead of full DateTime)

3. Part

 SelectMany((dayGroupWithMaxTime) =>
        dayGroupWithMaxTime.
            DayGroup.
            Where(data =>
                (data.TimeStamp == dayGroupWithMaxTime.MaxTimeInDay)));

From each group(for each day) selects all record with maximal time in day, just simply comparing each record’s TimeStamp with maximal in day(for his current group(day)):

 dayGroupWithMaxTime.
     DayGroup.
     Where(data =>
               (data.TimeStamp == dayGroupWithMaxTime.MaxTimeInDay))

solved How to filter data based on maximum datetime value in each day [closed]