csharp比较列表<t>从左到右和从右到左

时间:2016-10-14 21:55:38

标签: c# list-comparison

来自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     噢,Kam Foo     丰岛,蒂姆     盖伊,Wey Yuan     加西亚,黛布拉      * /

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

2 个答案:

答案 0 :(得分:2)

考虑Enumerable.Reverse

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

或者,可能更有效率,反转结果,如 @JianpingLiu 建议:

IEnumerable<string> differenceQuery = names1.Except(names2).Reverse();

答案 1 :(得分:1)

您的意思是想要names2中的文字而不是names1中的文字吗?如果有,请尝试names2.Except(names1)

如果您正在寻找名称1和名称2相交之外的所有内容,请检查此答案The opposite of Intersect()

相关问题