0

我有下一个文件:timesBetweenStartToEnd.txt其中包含:

Starting at: 12:15:28 -> Ending at: 12:17:38 -> 130 Seconds
Starting at: 12:12:18 -> Ending at: 12:12:38 -> 20 Seconds
.....

我想按秒数对其进行排序,并将排序后的行插入另一个名为:logTimes.txt.

我尝试了下一件事:

string[] scores = System.IO.File.ReadAllLines("timesBetweenStartToEnd.txt");
var orderedScores = scores.OrderByDescending(x => int.Parse(x.Split(' ')[8]
.Substring(0,scores.IndexOf(" "))); // here I have an error because of `scores.`, I neead an index

foreach (var score in orderedScores)
{
     System.IO.File.AppendAllText(@"logTimes.txt", string.Format("{0}{1}", orderedScores, Environment.NewLine));
}

所以,logTimes.txt应该包含(降序):

Starting at: 12:15:28 -> Ending at: 12:17:38 -> 130 Seconds
Starting at: 12:12:18 -> Ending at: 12:12:38 -> 20 Seconds

任何帮助表示赞赏!

4

4 回答 4

3

如果格式很严格,这将有效:

var orderedLines = File.ReadLines("timesBetweenStartToEnd.txt")
    .Select(l =>
    {
        int secondsIndex = l.LastIndexOf(" -> ");
        int? sec = (int?)null;
        if(secondsIndex != -1)
        {
            secondsIndex += " -> ".Length;
            int secondEndIndex = l.IndexOf(" Seconds", secondsIndex);
            if (secondEndIndex != -1)
            {
                int length = secondEndIndex - secondsIndex;
                string secondsPart = l.Substring(secondsIndex, length).Trim();
                int seconds;
                if (int.TryParse(secondsPart, out seconds))
                    sec = (int?)seconds;
            }
        }
        return new { Line = l, Seconds = sec };
    })
    .OrderBy(x => x.Seconds)
    .Select(x => x.Line);
File.WriteAllLines("logTimes.txt", orderedLines);

由于我选择了a如果您只想记录有效行,Nullable<int>您可以简单地添加 a :Where

...
.Where(x => x.Seconds.HasValue)
.OrderBy(x => x.Seconds.Value)
.Select(x => x.Line);
于 2013-06-19T09:43:10.483 回答
1

尝试使用以下更正:

string[] scores = System.IO.File.ReadAllLines("timesBetweenStartToEnd.txt");
var orderedScores = scores.OrderBy(x => int.Parse(x.Split(' ')[8].Split(' ')[0]));

foreach (var score in orderedScores)
{
     System.IO.File.AppendAllText(@"logTimes.txt", string.Format("{0}{1}", score, Environment.NewLine));
}

请注意,此解决方案对正确的语法很敏感,如果任何行与您的示例行不匹配,则会抛出异常。

于 2013-06-19T09:45:01.507 回答
1

问题是您尝试引用由 lambda 语句处理的当前数组元素。但是在您的声明中,您不使用它,而是使用整个数组。将行更改为:

var orderedScores = scores.OrderByDescending(x => int.Parse(x.Split(' ')[8]
.Substring(0,x.IndexOf(" ")));
于 2013-06-19T09:43:10.527 回答
1
var orderedScores = scores.OrderBy(x => int.Parse(x.Substring(x.LastIndexOf("->"),  
x.IndexOf("Seconds") - x.LastIndexOf("->")).Trim("-->".ToCharArray()).Trim()));  

如果您根据最后的秒值进行安排。这可能会帮助你

于 2013-06-19T09:52:13.200 回答