2

特定の単語を含む行の前にある行のリストを取得しようとしています。これが私のスクリプトです:

private static void Main(string[] args)
{
    int counter = 0;
    string line;

    System.IO.StreamReader file = new System.IO.StreamReader("E:\\overview2.srt");
    List<string> lines = new List<string>();
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains("medication"))
        {


            int x = counter - 1;
            Console.WriteLine(x); // this will write the line number not its contents

        }

        counter++;
    }

    file.Close();
}
4

4 に答える 4

2

LINQメソッド構文の使用:

var lines = File.ReadLines("E:\\overview2.srt")
        .Where(line => line.Contains("medication"))
        .ToList();

およびLINQキーワード構文:

var lines = (
    from line in File.ReadLines("E:\\overview2.srt")
    where line.Contains("medication")
    select line
).ToList();

配列が必要な場合は、の.ToArray()代わりにを使用して.ToList()ください。

また、必要なのが行を1回繰り返すことだけである場合は、ToArrayまたはToList:を気にしないでください。

var query = 
    from line in File.ReadLines("E:\\overview2.srt")
    where line.Contains("medication")
    select line;
foreach (var line in query) {
    Console.WriteLine(line);
}
于 2012-12-30T08:09:43.903 に答える
0

を作成できますQueue<string>。あなたがそれを通過するときにそれに各行を追加します。必要な行数を超えている場合は、最初のアイテムをデキューします。必要な検索式Queue<string>を押すと、出力する必要のあるすべての行が含まれます。

File.ReadAllLinesまたは、メモリがオブジェクトでない場合は、 (http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspxを参照)を使用して、配列にインデックスを付けることができます。

于 2012-12-30T06:55:42.723 に答える
0

これを試して:

 int linenum = 0;
                foreach (var line in File.ReadAllLines("Your Address"))
                {
                    if (line.Contains("medication"))
                    {
                        Console.WriteLine(string.Format("line Number:{} Text:{}"linenum,line)
//Add to your list or ...
                    }
                    linenum++;
                }
于 2012-12-30T06:57:23.237 に答える
0

このコードは、検索テキストを含む行の直前のすべての行を表示します。

    private static void Main(string[] args)
    {
        string cacheline = "";
        string line;

        System.IO.StreamReader file = new System.IO.StreamReader("C:\\overview2.srt");
        List<string> lines = new List<string>();
        while ((line = file.ReadLine()) != null)
        {
            if (line.Contains("medication"))
            {
                lines.Add(cacheline);
            }
            cacheline = line;
        }
        file.Close();

        foreach (var l in lines)
        {
            Console.WriteLine(l);           
        }
    }

見つかった行の前にあるすべての行を探しているのか、1行だけを探しているのかを、質問から判断するのは困難です。(検索テキストが最初の行にあるという特殊なケースに対処する必要があります)。

于 2012-12-30T07:08:45.310 に答える