bool hasDuplicate = false;
int[] a = new int[] {1, 2, 3, 4};int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
我需要将数组A的所有元素与数组B的元素进行比较,如果B中有重复的元素,则将true设置为hasDuplicate。
我使用“IndexOf”和“foreach”循环来创建它。 (注意:前3个“字符串”行只是一个如何创建数组并使其成为正确格式的示例)。
如果要比较2个数组,它们将以分号分隔,但最后一个值后面没有一个数组。如果在数组的字符串形式中附加一个分号(即a; b; c变为a; b; c;),则可以使用“x;”匹配无论它处于什么位置:
bool found = false;string someString = "a-b-c";string[] arrString = someString.Split('-');string myStringArray = arrString.ToString() + ";";foreach (string s in otherArray)
{ if (myStringArray.IndexOf(s + ";") != -1) {
found = true; break;
}
}if (found == true) {
// ....}
public bool Checking()
{ bool hasDuplicate = false; int[] a = new int[] { 1, 2, 3, 4 }; int[] b = new int[] { 5, 6, 1, 2, 7, 8 };int count = a.Intersect(b).Count(); if (count >= 1)
hasDuplicate = true;return hasDuplicate;
我用for
循环完成了它。关键是我们将每个成员与数组b
中的成员进行比较。因此,首先将a[0]
与数组b
中的每个成员进行比较,然后转到a[1]
并执行相同操作,依此类推,直到找到匹配项。
bool hasDuplicate = false;int[] a = new int[] { 1, 2, 3, 4 };int[] b = new int[] { 5, 6, 1, 2, 7, 8 };for (int i = 0; i < a.Length; i++)
{ for (int j = 0; j < b.Length; j++)
{ if (a[i] == b[j])
{
hasDuplicate = true;
}
}
}