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);

を選択したので、有効な行のみをログに記録Nullable<int>する場合は、単純に追加できます。Where

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

問題は、ラムダ ステートメントによって処理される現在の配列要素を参照しようとすることです。しかし、ステートメントではそれを使用せず、代わりに配列全体を使用します。行を次のように変更します。

var orderedScores = scores.OrderByDescending(x => int.Parse(x.Split(' ')[8]
.Substring(0,x.IndexOf(" ")));
于 2013-06-19T09:43:10.527 に答える
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 に答える