Martin
Martin

Reputation: 21

List with dates, times and a string ref

I have a sorted list of data to populate a gridview control. The list is ordered by datetime

I need to find the most recent 3 times per unique ref within each day (there may be more than 1 unique refs within a day). If there is only 1 ref row within a day then it is to be ignored.

I suppose it needs to be chunked into days and refs, then ordered by most recent with a count of refs within that 'chunk'. Any ideas appreciated.

It's a standard list of objects (the object has Date, Time and Ref properties) as:

    private List<Reading> _listReadings = new List<Reading>(); 

and is bound to a grid:

    DataRow newRow = MyTable.NewRow();
    newRow.ItemArray = new object[]
    {
        new 
        DateTime(_listReadings.TimeStamp.Year,listReadings.TimeStamp.Month),
        GetTime(_listReadings.TimeStamp),
        _listReadings.Ref,
    };
    MyTable.Rows.Add(newRow);

Upvotes: 1

Views: 129

Answers (1)

Slate
Slate

Reputation: 3694

  • Given a backing source of List<Reading>,
  • Group your source data by day using GroupBy
  • For-each day (the value in the group):
    • Group your source data by ref using GroupBy
    • Test if the group has 3+ values, or filter the ones that do not (Where and Count)
    • Order by datetimes of the values using OrderByDescending (latest is first)
    • Take 3 dates

So something like this:

    public static IEnumerable<Reading> Filter(List<Reading> readings)
    {
        List<Reading> result = new List<Reading>();

        var dayGroupings = readings.GroupBy(r => r.Day);
        foreach (var dayGroup in dayGroupings)
        {
            var refGroupings = dayGroup.GroupBy(g => g.Ref);
            foreach (var refGroup in refGroupings.Where(g => g.Count() >= 3))
            {
                result.AddRange(refGroup.OrderByDescending(g => g.Time).Take(3));
            }         
        }
        return result;
    }

Upvotes: 1

Related Questions