比较两个string数组的C#

好的,所以这可能是一个基本的问题,但我将不胜感激。

假设我们有5个string数组:

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"}; 

有没有一种方法比较这些string彼此没有在C#中循环,只有一个和C会产生布尔真正? 换句话说,所有的元素必须相同,数组必须是相同的大小? 再次,如果可能,不使用循环。 提前致谢!

你可以使用Linq:

 bool areEqual = a.SequenceEqual(b); 

尝试使用Enumerable.SequenceEqual :

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

如果你想一口气把它们全部比较:

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

返回两个匹配(你可能扩大这个排除已经匹配的项目,我想)

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