1

Hi guys i have a string Enumerable which consist of laptimes in this format "00:30" "1:50" (min:sec). And my ultimate goal is to return an enumerable that consists of TimeSpans of time differences between each time with these string objects converted into TimeSpans.

So for example if we have this: "00:30" "1:50" " "2:00" this will return 00:30 , 1:20 , 0:10.

I currently have this:

var laps = lapTimes.Select(s => TimeSpan.ParseExact(s, "mm:ss", System.Globalization.CultureInfo.CurrentCulture)

But it is not able to parse it. Also i dont know how i would do the time difference using linq because if i try subtracting the current time span from the one in the next index eventually i will receive an index out of bound exception.

Thanks , would appreciate the help.

4

4 回答 4

1

当您在迭代时需要前一个项目时,我认为 LINQ 不适合您的情况。

string format = @"h\:mm";
string[] laps = new[]{"00:30", "1:50", "2:00"};

var spans = new List<TimeSpan>();
spans.Add(TimeSpan.ParseExact(laps[0], format, null));

for (int i = 1; i < laps.Length; i++)
{
    spans.Add(
        TimeSpan.ParseExact(laps[i   ], format, null) -
        TimeSpan.ParseExact(laps[i -1], format, null)
        );
}
于 2013-09-05T21:00:14.733 回答
0

I would use DateTime.ParseExact. Then you can use the indexer of the ordered List to access the previous TimeSpan and subtract it from the next TimeSpan:

var lapTimes = new[]{"00:30", "1:50","2:00"};
var laps = lapTimes.Select(s => DateTime.ParseExact(s, "m:ss", null).TimeOfDay)
    .OrderBy(ts => ts)
    .ToList();
var diffs = laps.Take(1)   // take the first fix TimeSpan
    .Concat(laps.Skip(1).Select((ts, i) => ts - laps[i])) // add all differences
    .ToList();

DEMO

Edit: For the sake of completeness, i always forget that you need to escape the colons in TimeSpan.ParseExact, so this works also:

var laps = lapTimes.Select(s => TimeSpan.ParseExact(s, @"m\:ss", null))
    ....

Details: Custom TimeSpan Format Strings

于 2013-09-05T20:51:30.313 回答
0
One solution:

string[] lapTimes = { "00:30", "1:50", "2:00"};
var laps = lapTimes.Select(s => s.Split(":".ToCharArray()));
var times = laps.Select(s=> new TimeSpan(0, int.Parse(s[0]), int.Parse(s[1]))).Reverse();
List<TimeSpan> diffs = new List<TimeSpan>();
for (int i = 0; i < times.Count() - 1; i++)
{
    diffs.Add(times.ElementAt(i) - times.ElementAt(i+1));            
}
于 2013-09-05T20:54:20.060 回答
0

它不是 LINQ,但这也可以通过foreach循环来完成:

List<string> stringList = new List<string>();
stringList.Add("00:30");
stringList.Add("01:50");
stringList.Add("02:00");

List<TimeSpan> timeSpanList = new List<TimeSpan>();
TimeSpan ts1 = new TimeSpan(0, 0, 0);
TimeSpan ts2 = new TimeSpan(0, 0, 0);

foreach (string item in stringList)
{
    ts1 = TimeSpan.ParseExact(item, @"mm\:ss", System.Globalization.CultureInfo.CurrentCulture);

    if (ts2.Equals(new TimeSpan(0,0,0)))
    {
        timeSpanList.Add(ts1);
    }
    else
    {
        timeSpanList.Add(ts1 - ts2);
    }

    ts2 = ts1;
}
于 2013-09-05T20:54:52.347 回答