按每行编号对文件进行排序,然后将其插入到另一个文件中
本文关键字:文件 插入 另一个 然后 排序 编号 | 更新日期: 2023-09-27 18:18:57
我有下一个文件: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
任何帮助表示赞赏!
如果格式严格,这可以有效地工作:
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);
问题是你试图引用由lambda语句处理的当前数组elemt。但是在你的语句中,你不使用它,而是使用整个数组。将行更改为:
var orderedScores = scores.OrderByDescending(x => int.Parse(x.Split(' ')[8]
.Substring(0,x.IndexOf(" ")));
var orderedScores = scores.OrderBy(x => int.Parse(x.Substring(x.LastIndexOf("->"),
x.IndexOf("Seconds") - x.LastIndexOf("->")).Trim("-->".ToCharArray()).Trim()));
如果您根据末尾的秒值进行排列。 这可能会对您有所帮助
尝试使用以下更正:
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));
}
请注意,此解决方案对正确的语法很敏感,如果任何行与您的示例行不匹配,则会引发异常。