1

I've seen examples of how to convert a string to a TimeSpan, here is one example:

How to Convert string "07:35" (HH:MM) to TimeSpan

But what is the most efficient way to convert a List<string> to List<TimeSpan>?

I've tried something along these lines, but isn't working:

var result = new TimeSpan;

var appointmentStartTimesConverted = appointmentStartTimes
  .Select(i => result = TimeSpan.TryParse(i, out result))
  .ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
the_tr00per
  • 439
  • 7
  • 23

5 Answers5

6

Should do the job:

 var appointmentStartTimes = new List<string>{"7:45", "0:0","a"};

 var appointmentStartTimesConverted = appointmentStartTimes
   .Select(i =>
            {
                TimeSpan result;
                if(TimeSpan.TryParse(i, out result))
                    return new Nullable<TimeSpan>(result);          
                return null;        
            })
   .Where(x => x.HasValue)
   .ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Lews Therin
  • 10,907
  • 4
  • 48
  • 72
4

No Linq solution - a simple loop is enough:

 List<TimeSpan> result = new List<TimeSpan>(appointmentStartTimes.Count);

 foreach (var item in appointmentStartTime)
   if (TimeSpan.TryParse(item, out var span)) // out var - C# 7.0 feature
     result.Add(span);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • This answer adresses the _most efficient_ emphasis by op. That said, the dual absence of brackets makes me feel naked. – Tewr May 24 '18 at 09:38
1

in below code, I'm having a list of string (which is supposed to have Timespan string but it can hold any string)

so first I'm checking for the condition if it passes TryParse and only then I am converting particular string into Timespan and add it into List of Timespan

List<string> str = new List<string>();
str.Add("07:30");
str.Add("amit");
TimeSpan res = new TimeSpan();
List<TimeSpan> ts = str.Where(x => TimeSpan.TryParse(x, out res) != false).Select(y => res).ToList();

This will take care of invalid time span string.

Amit
  • 1,821
  • 1
  • 17
  • 30
0

TryParse returns bool. Use Parse in try/catch block to ensure all values will be processed or use output parameter from TryParse
There is no need to declare local variable result.

var appointmentStartTimes = new List<string>();
//fill values here 

var appointmentStartTimesConverted = appointmentStartTimes
    .Select(i =>
        {
            try
            {
                return TimeSpan.Parse(i);
            }
            catch
            {
                return default(TimeSpan);
            }
        }
    ).ToList();

//anothey way
appointmentStartTimesConverted = appointmentStartTimes
    .Select(i =>
        {
            if (TimeSpan.TryParse(i, out var result))
                return result;

            return default(TimeSpan);
        }
    ).ToList();
Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18
0

I'd write something using Linq, but with an intermediate Function, like this:

        List<string> lst = new List<string>() { "7:35", "3:45", "0:23" };

        Func<string, TimeSpan> GetTS = (str) =>
        {
            TimeSpan.TryParse(str, out TimeSpan ts);
            return ts;
        };

        var tsLst = lst.Select(r => GetTS(r)).ToList();
Max Zeni
  • 3
  • 3
  • 1
    this is not good. you get default values and you dont know if default value is legitimate result or a failure. – M.kazem Akhgary May 24 '18 at 09:05
  • Yes, you're absolutely right. At first I thought TimeSpan TryParse would have given a null value in case of failure. I give count it's not true. Thanks, @M.kazemAkhgary – Max Zeni May 24 '18 at 10:06