Select Min time value for each day (linq)

mrw 201 Reputation points
2021-02-21T12:03:38.56+00:00

I have a table:

20.2.2021 12:54:34
20.2.2021 13:54:34
20.2.2021 14:54:34
20.2.2021 15:54:34
20.2.2021 16:54:34
21.2.2021 11:50:00
21.2.2021 13:54:34
21.2.2021 14:54:34
22.2.2021 10:00:00
22.2.2021 13:54:34
22.2.2021 14:54:34

I need to pick up 20.2.2021 12:54:34 & 21.2.2021 11:50:00 & 22.2.2021 10:00:00 and calculate average time.

Here is my current code:

List<TimeSpan> result = db.Log
.Where(w => w.DateToday.Date >= startDate.Date && w.DateToday.Date <= endDate.Date)
  .Select(a => a.DateToday.TimeOfDay)
  .ToList();

double doubleAverageTicks = result.Average(timeSpan => timeSpan.Ticks);
long longAverageTicks = Convert.ToInt64(doubleAverageTicks);

return new TimeSpan(longAverageTicks);

It is capable to calculate average, but it is currently taking all dates and calculating average. I need to select only first (Min) time record each day. How to achieve that?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,535 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114K Reputation points
    2021-02-21T14:34:54.56+00:00

    To get the dates, try a query like this:

    IEnumerable<DateTime> days_min_time = 
        db.Log
            .Select( d => d.DateToday )
            .GroupBy( g => g.Date )
            .Select( g => g.Min( ) );
    

    Then perform other operations.

    0 comments No comments

0 additional answers

Sort by: Most helpful