-1

来自https://msdn.microsoft.com/en-us/library/mt693040.aspx的字符串列表可以通过 linq 使用以下代码进行比较。有没有内置的方法来比较从左到右和从右到左的列表?

class CompareLists
{        
    static void Main()
    {
        // Create the IEnumerable data sources.
        string[] names1 = System.IO.File.ReadAllLines(@"../../../names1.txt");
        string[] names2 = System.IO.File.ReadAllLines(@"../../../names2.txt");

        // Create the query. Note that method syntax must be used here.
        IEnumerable<string> differenceQuery =
          names1.Except(names2);

        // Execute the query.
        Console.WriteLine("The following lines are in names1.txt but not names2.txt");
        foreach (string s in differenceQuery)
            Console.WriteLine(s);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

/* 输出:以下行在 names1.txt 但不在 names2.txt Potra、Cristina Noriega、Fabricio Aw、Kam Foo Toyoshima、Tim Guy、Wey Yuan Garcia、Debra */

注意:从左到右表示源列表到目标列表,反之亦然。

4

2 回答 2

2

考虑Enumerable.Reverse

string[] names1 = File.ReadAllLines(@"../../../names1.txt")
                      .Reverse()
                      .ToArray();

或者,正如@JianpingLiu建议的那样,扭转结果可能更有效:

IEnumerable<string> differenceQuery = names1.Except(names2).Reverse();
于 2016-10-14T22:05:14.330 回答
1

你的意思是你想要文本names2而不是 in names1?如果是这样试试names2.Except(names1)

如果您正在寻找 names1 和 names2 相交之外的所有内容,请查看此答案Intersect() 的反面

于 2016-10-14T22:26:04.530 回答