比较 C# 中的两个字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17212254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:50:54  来源:igfitidea点击:

Comparing two string arrays in C#

c#.netstringlinqequality

提问by Wes Field

Say we have 5 string arrays as such:

假设我们有 5 个字符串数组:

string[] a = {"The","Big", "Ant"};
string[] b = {"Big","Ant","Ran"};
string[] c = {"The","Big","Ant"};
string[] d = {"No","Ants","Here"};
string[] e = {"The", "Big", "Ant", "Ran", "Too", "Far"};

Is there a method to compare these strings to each other without looping through them in C# such that only a and c would yield the boolean true? In other words, all elements must be equal and the array must be the same size? Again, without using a loop if possible.

有没有一种方法可以将这些字符串相互比较而无需在 C# 中循环遍历它们,这样只有 a 和 c 会产生布尔值 true?换句话说,所有元素必须相等并且数组必须相同大小?同样,如果可能,不使用循环。

采纳答案by Ahmed KRAIEM

You can use Linq:

您可以使用 Linq:

bool areEqual = a.SequenceEqual(b);

回答by Darren

Try using Enumerable.SequenceEqual:

尝试使用Enumerable.SequenceEqual

var equal = Enumerable.SequenceEqual(a, b);

回答by Charleh

If you want to compare them all in one go:

如果您想一口气比较它们:

string[] a = { "The", "Big", "Ant" };
string[] b = { "Big", "Ant", "Ran" };
string[] c = { "The", "Big", "Ant" };
string[] d = { "No", "Ants", "Here" };
string[] e = { "The", "Big", "Ant", "Ran", "Too", "Far" };

// Add the strings to an IEnumerable (just used List<T> here)
var strings = new List<string[]> { a, b, c, d, e };

// Find all string arrays which match the sequence in a list of string arrays
// that doesn't contain the original string array (by ref)
var eq = strings.Where(toCheck => 
                            strings.Where(x => x != toCheck)
                            .Any(y => y.SequenceEqual(toCheck))
                      );

Returns both matches (you could probably expand this to exclude items which already matched I suppose)

返回两个匹配项(您可以扩展它以排除我认为已经匹配的项目)

回答by Dejan Ciev

        if (a.Length == d.Length)
        {
            var result = a.Except(d).ToArray();
            if (result.Count() == 0)
            {
                Console.WriteLine("OK");
            }
            else
            {
                Console.WriteLine("NO");
            }
        }
        else
        {
            Console.WriteLine("NO");
        }

回答by Manish Vadher

if you want to get array data that differ from another array you can try .Except

如果你想获得与另一个数组不同的数组数据,你可以尝试 .Except

string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "aa" };

string[] DifferArray = array1.Except(array2).ToArray();

Output:{"bb","cc"}

输出:{"bb","cc"}