在Java中,arrays .equals()允许轻松地比较两个基本数组的内容(重载可用于所有基本类型)。
c#中有这样的东西吗?在c#中是否存在比较两个数组内容的“神奇”方法?
在Java中,arrays .equals()允许轻松地比较两个基本数组的内容(重载可用于所有基本类型)。
c#中有这样的东西吗?在c#中是否存在比较两个数组内容的“神奇”方法?
当前回答
SequenceEqual只在满足两个条件时才返回true。
它们包含相同的元素。 元素的顺序是一样的。
如果您只想检查它们是否包含相同的元素,而不管它们的顺序如何,那么您的问题属于
values2是否包含values1中包含的所有值?
可以使用LINQ扩展方法Enumerable。Except,然后检查结果是否有任何值。这里有一个例子
int[] values1 = { 1, 2, 3, 4 };
int[] values2 = { 1, 2, 5 };
var result = values1.Except(values2);
if(result.Count()==0)
{
//They are the same
}
else
{
//They are different
}
通过这个你也可以自动得到不同的项目。一石二鸟。
请记住,如果像这样执行代码
var result = values2.Except(values1);
你会得到不同的结果。
在我的例子中,我有一个数组的本地副本,想要检查是否有任何东西已经从原始数组中删除,所以我使用这个方法。
其他回答
检查这个线程的答案,它将其中一个数组转换为HashSet,并使用SetEquals与另一个数组进行比较。 但是请注意,这并不检查顺序或副本。
我在视觉工作室做了这个,效果非常好;用简短的此代码逐个索引地比较数组。
private void compareButton_Click(object sender, EventArgs e)
{
int[] answer = { 1, 3, 4, 6, 8, 9, 5, 4, 0, 6 };
int[] exam = { 1, 2, 3, 6, 8, 9, 5, 4, 0, 7 };
int correctAnswers = 0;
int wrongAnswers = 0;
for (int index = 0; index < answer.Length; index++)
{
if (answer[index] == exam[index])
{
correctAnswers += 1;
}
else
{
wrongAnswers += 1;
}
}
outputLabel.Text = ("The matching numbers are " + correctAnswers +
"\n" + "The non matching numbers are " + wrongAnswers);
}
输出将是;匹配的数字是7 不匹配的数字是3
你可以使用Enumerable.SequenceEqual。这适用于任何IEnumerable<T>,而不仅仅是数组。
对于某些应用可能更好:
string.Join(",", arr1) == string.Join(",", arr2)
int[] a = { 2, 1, 3, 4, 5, 2 };
int[] b = { 2, 1, 3, 4, 5, 2 };
bool ans = true;
if(a.Length != b.Length)
{
ans = false;
}
else
{
for (int i = 0; i < a.Length; i++)
{
if( a[i] != b[i])
{
ans = false;
}
}
}
string str = "";
if(ans == true)
{
str = "Two Arrays are Equal";
}
if (ans == false)
{
str = "Two Arrays are not Equal";
}
//--------------Or You can write One line of Code-------------
var ArrayEquals = a.SequenceEqual(b); // returns true