2

2 つの foreach ループがあり、それぞれがテキスト ファイルをループし、最初の 2 列のみのすべての値の値を取得し (テキスト ファイルには "|" で区切られた 2 つ以上の列があります)、それを文字列にします。これらの foreach ループの結果 (ステートメントによって出力される値) を比較してResponse.Write、文字列が等しいかどうかを確認したいと思います。任意の考え/提案をいただければ幸いです。

protected void Page_Load(object sender, EventArgs e)
{
    string textFile1 = @"C:\Test\Test1.txt";
    string textFile2 = @"C:\Test\Test2.txt";
    string[] textFile1Lines = System.IO.File.ReadAllLines(textFile1);
    string[] textFile2Lines = System.IO.File.ReadAllLines(textFile2);
    char[] delimiterChars = { '|' };

    foreach (string line in textFile1Lines)
    {
        string[] words = line.Split(delimiterChars);
        string column1And2 = words[0] + words[1];
        Response.Write(column1And2);
    }

    foreach (string line in textFile2Lines)
    {
        string[] words = line.Split(delimiterChars);
        string column1And2 = words[0] + words[1];
        Response.Write(column1And2);
    }
}
4

2 に答える 2

2

出力を比較する 1 つの方法は、文字列を保存してから、 を使用して結果を比較することSequenceEqualです。2 つのループは同一であるため、それらから静的メソッドを作成することを検討してください。

// Make the extraction its own method
private static IEnumerable<string> ExtractFirstTwoColumns(string fileName) {
    return System.IO.File.ReadLines(fileName).Select(
         line => {
              string[] words = line.Split(delimiterChars);
              return words[0] + words[1];
         }
    );
}

protected void Page_Load(object sender, EventArgs e)
    // Use extraction to do both comparisons and to write
    var extracted1 = ExtractFirstTwoColumns(@"C:\Test\Test1.txt").ToList();
    var extracted2 = ExtractFirstTwoColumns(@"C:\Test\Test2.txt").ToList();
    // Write the content to the response
    foreach (var s in extracted1) {
        Response.Write(s);
    }
    foreach (var s in extracted2) {
        Response.Write(s);
    }
    // Do the comparison
    if (extracted1.SequenceEqual(extracted2)) {
        Console.Error.WriteLine("First two columns are different.");
    }
}
于 2013-08-26T19:20:37.343 に答える