0

I have a string list holding time values in this format: 11:25:46.123, I would like to be able to find highest and lowest time value from this list. How can I do it?

I tried something like this, but I am not sure if it is correct and I don't know what to do next.

List<TimeSpan> time = StringList.Select(x => TimeSpan.ParseExact(x, "HH:mm:ss.fff", null)).ToList();

EDIT: I am getting error:

Input string was not in a correct format.
Michal_LFC
  • 649
  • 3
  • 11
  • 25
  • So what is your question? How to get max/min? or how to parse a string list? (as that is what you have an error with). I would suggest editing your question and picking one or the other, not both – musefan Sep 03 '13 at 09:49
  • At the beggining my question was about min/max values, but now I see that I have error in prasing! – Michal_LFC Sep 03 '13 at 09:50

4 Answers4

7

I am getting error: Input string was not in a correct format.

Your timespan format is not correct. Try this

var StringList = new[] { "21:25:46.123" };
List<TimeSpan> time = StringList
                      .Select(x => TimeSpan.ParseExact(x, @"hh\:mm\:ss\.fff", null))
                      .ToList();
var max = time.Max();
var min = time.Min();
EZI
  • 15,209
  • 2
  • 27
  • 33
  • 3
    @musefan try and see. – EZI Sep 03 '13 at 09:52
  • 1
    Exactly what I wanted. Working perfectly!! Thank you. :D – Michal_LFC Sep 03 '13 at 09:53
  • @musefan Why that format ..check this http://stackoverflow.com/questions/12036972/timespan-parseexact-giving-error/12037072#12037072 – V4Vendetta Sep 03 '13 at 10:00
  • @musefan [Custom format strings for `TimeSpan`](http://msdn.microsoft.com/en-us/library/ee372287.aspx) where introduced in .NET 4.0 (Visual Studio 2010) and are distinct from format strings for `DateTime`. In particular, they don't allow a naked colon, and there is no need to discriminate between `HH` and `hh`. – Jeppe Stig Nielsen Sep 03 '13 at 10:20
  • 2
    Note that Linq methods `.Max()` and `.Min()` will throw if the list is empty (for non-nullable types). – Jeppe Stig Nielsen Sep 03 '13 at 10:22
4

Have you tried:

TimeSpan maxTimeSpan = time.Max();
TimeSpan minTimeSpan = time.Min();
dcastro
  • 66,540
  • 21
  • 145
  • 155
4

Try this

TimeSpan _maxtime= time.Max(); // For max time
TimeSpan _mintime= time.Min();// For min time

also take a look at MSDN

Rohit
  • 10,056
  • 7
  • 50
  • 82
2

Try without using ParseExact

List<TimeSpan> times = StringList
    .Select(x => TimeSpan.Parse(x))
    .OrderBy(ts => ts)
    .ToList();
TimeSpan shortest = times.First();
TimeSpan longest = times.Last();
Ronak Patel
  • 2,570
  • 17
  • 20