59

假设我们有 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"};

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

4

5 回答 5

104

You can use Linq:

bool areEqual = a.SequenceEqual(b);
于 2013-06-20T11:20:19.097 回答
21

尝试使用Enumerable.SequenceEqual

var equal = Enumerable.SequenceEqual(a, b);
于 2013-06-20T11:21:22.437 回答
5

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

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

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

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

于 2018-03-17T09:05:48.340 回答
3

如果您想一次性比较它们:

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))
                      );

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

于 2013-06-20T11:34:27.470 回答
-2
        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");
        }
于 2013-06-22T16:13:57.083 回答