2

我有两个 foreach 循环,每个循环都遍历一个文本文件,并仅获取前两列的所有值的值(文本文件中有两列以上,由“|”分隔)并放置它在一个字符串中。我想比较这些 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

比较输出的一种方法是随时存储字符串,然后使用SequenceEqual. 由于这两个循环是相同的,请考虑用它们制作一个静态方法:

// 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 回答
1

我会简单地在同一个循环中比较,使用 for 而不是 foreach:

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 = { '|' };

    if (textFile1Lines.Count != textFile2Lines.Count)
    {
        // Do something since the line counts don't match
    }
    else
    {

    foreach (int i = 0; i < textFile1Lines.Count; i++)
    {
        string[] words1 = textFile1Lines[i].Split(delimiterChars);
        string compareValue1 = words1[0] + words1[1];

        string[] words2 = textFile2Lines[i].Split(delimiterChars);
        string compareValue2 = words2[0] + words2[1];

        if (!string.Equals(compareValue1, compareValue2))
        {
            // Do something
            break; // Exit the loop since you found a difference
        }
    }
}
}
于 2013-08-26T19:32:53.297 回答