Shijith MC
Shijith MC

Reputation: 139

Find max time from string list

I want to find max time from a list of time formats, Its not exactly TimeSpan so parsing it won't help. Please suggest a solution.

var duration = new List<string>() { "116:48:28", "110:36:28", "16:30:28"};
var maxts = duration.Max(x => TimeSpan.Parse(x));

Upvotes: 2

Views: 480

Answers (4)

rory.ap
rory.ap

Reputation: 35270

You could use a regex:

internal static TimeSpan ParseSpecialTimespan(string toParse)
{
    string pattern = @"^(\d+):([0-5]?\d{1}):([0-5]?\d{1})$";

    var match = Regex.Match(toParse, pattern);
    if (!match.Success) throw new ArgumentException(@"The provided string is not valid...");
    int hours = int.Parse(match.Groups[1].ToString());
    int minutes = int.Parse(match.Groups[2].ToString());
    int seconds = int.Parse(match.Groups[3].ToString());
    TimeSpan t = new TimeSpan(hours, minutes, seconds);
    return t;
}

Here's how it's used:

var duration = new List<string>() { "116:48:28", "110:36:28", "16:30:28" };
string largestInput = "";
TimeSpan largestTimespan = new TimeSpan(0);

foreach (string d in duration)
{
    TimeSpan parse = ParseSpecialTimespan(d);

    if (parse > largestTimespan)
    {
        largestTimespan = parse;
        largestInput = d;
    }
}

System.Diagnostics.Debug.Print(@"Largest timespan is ""{0}"" from input ""{1}"".", largestTimespan.ToString(), largestInput); 

Upvotes: 0

Maksim Simkin
Maksim Simkin

Reputation: 9679

You could try this. it will work in case, that you don't have something such as "1:70:10"...

duration.Select(d=>d.Replace(":", string.Empty)).Select(int.Parse).OrderBy(s=>s)

Or, to get tha value of maximal timestamp:

duration.Select(d => new {Text =d, Val = int.Parse(d.Replace(":", string.Empty))})
        .OrderByDescending(x=>x.Val)
        .First()
        .Text;

Upvotes: 3

Roman
Roman

Reputation: 12171

You can use LINQ:

var sortedDuraion = duration
    .OrderByDescending((s) => Convert.ToInt32(s.Split(':')[0]))
    .ThenByDescending((s) => Convert.ToInt32(s.Split(':')[1]))
    .ThenByDescending((s) => Convert.ToInt32(s.Split(':')[2]));

var max = sortedDuration.ElementAt(0);

Also you can parse this string to int (delete ":") and order as int values:

var sortedDuration = duration.OrderByDescending((s) => Convert.ToInt32(s.Replace(":", String.Empty)));

var max = sortedDuration.ElementAt(0);

Upvotes: 2

Pranav Patel
Pranav Patel

Reputation: 1559

you can try like this

var duration = new List<string>() { "116:48:28", "110:36:28", "16:30:28" };
List<TimeSpan> lst = new List<TimeSpan>();
foreach (var item in duration)
{
    string[] data=item.Split(new char[]{':'});
    lst.Add(new TimeSpan(int.Parse(data[0]),int.Parse(data[1]),int.Parse(data[2])));
}
var max = lst.Max();

Upvotes: 0

Related Questions