我有下一个文件: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
任何帮助表示赞赏!
答案 0 :(得分: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);
由于我选择了Nullable<int>
,如果您只想记录有效行,则只需添加Where
即可:
...
.Where(x => x.Seconds.HasValue)
.OrderBy(x => x.Seconds.Value)
.Select(x => x.Line);
答案 1 :(得分:1)
问题是您尝试引用由lambda语句处理的当前数组elemt。但是在你的声明中你不使用它,而是使用整个数组。将行更改为:
var orderedScores = scores.OrderByDescending(x => int.Parse(x.Split(' ')[8]
.Substring(0,x.IndexOf(" ")));
答案 2 :(得分: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));
}
请注意,此解决方案对正确的语法很敏感,如果任何行与您的示例行不匹配,则会抛出异常。
答案 3 :(得分:1)
var orderedScores = scores.OrderBy(x => int.Parse(x.Substring(x.LastIndexOf("->"),
x.IndexOf("Seconds") - x.LastIndexOf("->")).Trim("-->".ToCharArray()).Trim()));
如果您根据最后的秒值进行排列。这可能对你有帮助