-9

How Can I calculate the average of a given List which content is described below:

06:56
06:58
06:55
06:54
06:54
06:53
06:55
06:53
06:58
06:54
06:58
06:55
06:54
06:50
06:54
06:57

Any idea ?!?

jep
  • 7
  • 1
  • 2

2 Answers2

9
        var times = new List<string>
        {
            "06:56",
            "06:58",
            "06:55",
            "06:54",
            "06:54",
            "06:53",
            "06:55",
            "06:53",
            "06:58",
            "06:54",
            "06:58",
            "06:55",
            "06:54",
            "06:50",
            "06:54",
            "06:57"
        };
        var average = times
            .Select(TimeSpan.Parse)
            .Average(x => x.TotalMilliseconds);

        var averageTime = TimeSpan.FromMilliseconds(average);
gabba
  • 2,815
  • 2
  • 27
  • 48
  • 1
    There is a variation here: [Find average of collection of timespans] http://stackoverflow.com/a/8847711/3527297 which averages on the ticks which (though not for the sample data here) may offer a higher precision for subsecond values. – Gustav Dec 04 '15 at 17:02
2

Convert the values to TimeSpan. The you can average directly with the output as the correct data type.

Addendum

Adding to the answer from @gabba providing a list of strings and the link above using ticks, you can calculate the average this way:

TimeSpan average = new TimeSpan(Convert.ToInt64(times.Average(x => TimeSpan.Parse(x).Ticks)));

The result value is, of course, the same: 06:54:52.500

Gustav
  • 53,498
  • 7
  • 29
  • 55