比较C#中的两个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11052132/
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
Comparing two arrays in C#
提问by GibboK
bool hasDuplicate = false;
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.
我需要将数组 A 的所有元素与数组 B 的元素进行比较,如果 B 中有重复元素,请将 hasDuplicate 设置为 TRUE。
采纳答案by vcsjones
Since this is Homework, I will give you a homework answer.
既然这是作业,我就给你一个作业答案。
Sure, you could use LINQ and rely on SequenceEqual, Intersect, etc, but that is likely not the point of the exercise.
当然,你可以使用LINQ和依赖SequenceEqual,Intersect等等,但是这很可能不是锻炼的点。
Given two arrays, you can iterate over the elements in an array using foreach.
给定两个数组,您可以使用 迭代数组中的元素foreach。
int[] someArray;
foreach(int number in someArray)
{
//number is the current item in the loop
}
So, if you have two arrays that are fairly small, you could loop over each number of the first array, then loop over the all the items in the second array and compare. Let's try that. First, we need to correct your array syntax. It should look something like this:
因此,如果您有两个相当小的数组,您可以遍历第一个数组的每个数字,然后遍历第二个数组中的所有项目并进行比较。让我们试试看。首先,我们需要更正您的数组语法。它应该是这样的:
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
Note the use of the curly braces {. You were using the syntax to create a N-dimensional array.
注意大括号的使用{。您正在使用语法来创建 N 维数组。
bool hasDuplicate = false;
int[] a = new int[] { 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
foreach (var numberB in b)
{
//Something goes here
}
}
This gets us pretty close. I'd encourage you to try it on your own from here. If you still need help, keep reading.
这让我们非常接近。我鼓励你从这里自己尝试。如果您仍然需要帮助,请继续阅读。
OK, so we basically need to just check if the numbers are the same. If they are, set hasDuplicateto true.
好的,所以我们基本上只需要检查数字是否相同。如果是,则设置hasDuplicate为 true。
bool hasDuplicate = false;
int[] a = new int[] { 8, 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
foreach (var numberB in b)
{
if (numberA == numberB)
{
hasDuplicate = true;
}
}
}
This is a very "brute" force approach. The complexity of the loop is O(n2), but that may not matter in your case. The other answers using LINQ are certainly more efficient, and if efficiency is important, you could consider those. Another option is to "stop" the loops using breakif hasDuplicateis true, or place this code in a method and use returnto exit the method.
这是一种非常“蛮力”的方法。循环的复杂性是 O(n 2),但这在您的情况下可能无关紧要。使用 LINQ 的其他答案肯定更有效,如果效率很重要,您可以考虑这些。另一种选择是使用breakif hasDuplicateis true来“停止”循环,或者将此代码放在一个方法中并用于return退出该方法。
回答by Jakub Konecki
hasDuplicates = a.Intersect(b).Any();
You can use LINQ Intersectmethod - http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx
您可以使用 LINQIntersect方法 - http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx
回答by phadaphunk
I know you don't want a one line solution but I'll leave my answer for other users who might want a simple solution for the same problem.
我知道您不想要单行解决方案,但我会将我的答案留给可能需要针对同一问题的简单解决方案的其他用户。
If you don't want to use Linq, you could use SequenceEqual.
如果您不想使用Linq,则可以使用SequenceEqual。
bool equal = Array1.SequenceEqual(Array2);
bool equal = Array1.SequenceEqual(Array2);
Hope it helps.
希望能帮助到你。
回答by banging
If learning is what you seek and an algo is what you're trying to come up with, then using LINQ and any other jazz won't help you.
如果学习是你所寻求的,而算法是你试图提出的,那么使用 LINQ 和任何其他爵士乐都不会帮助你。
You need to have 2 nested foreach(or for, whichever you prefer) loops, and once you found a member in the first loop matching a member in the second loop, set your boolean variable to true and breakthe loops
您需要有 2 个嵌套foreach(或for,无论您喜欢哪个)循环,并且一旦您在第一个循环中找到与第二个循环中的成员匹配的成员,请将您的布尔变量设置为 true 并且break循环
回答by Mario
Not the most performant, but probably easiest to understand approach would be something like this:
不是最高效的,但可能最容易理解的方法是这样的:
foreach (int _a in a) { // iterate through all elements in array a (as _a)
foreach (int _b in b) { // iterate through all elements in array b (as _b)
if (_a == _b) { // if we've got a duplicate
hasDuplicates = true; // store that for later on
break; // immediately leave this loop (no point in further looking up)
}
}
if (hasDuplicates) { // if we've got a duplicate
break; // leave this loop as well (no point in further looking up)
}
}
Obviously, this is not the most performant solution as the complexity would be O(n2), which means twice the number of elements in any one array will double the amount of time it takes to complete the operation (worst case); twice the number of elements in both arrays will quadruple the amount of time.
显然,这不是性能最好的解决方案,因为复杂性是O(n2),这意味着任何一个数组中元素数量的两倍将使完成操作所需的时间加倍(最坏情况)两个数组中元素数量的两倍将使时间增加四倍。
More elegant solutions would be the use of predefined methos as described in some of the other solutions, but due to this being homework stuff, I don't expect you're allowed to use these "shortcuts" (or should do so).
更优雅的解决方案是使用其他一些解决方案中描述的预定义方法,但由于这是家庭作业,我不希望您被允许使用这些“快捷方式”(或应该这样做)。
Always remember: Even if you find solutions here, try to understand them, use them for inspiration, and then write your own. That's probably the best way to learn. Don't just copy & paste.
永远记住:即使你在这里找到了解决方案,也要试着去理解它们,用它们来获得灵感,然后写出你自己的。这可能是最好的学习方式。不要只是复制和粘贴。
回答by Shyju
Eventhough LINQwill help you to do this with one line of code, It is better to understand how it works because you mentioned the word Algorithmin your question :)
尽管LINQ将帮助您用一行代码完成此操作,但最好了解它的工作原理,因为您在问题中提到了算法一词:)
Loop thru the array and compare each item with the items in the second array. If it is present, return true. else false. I would wrap that in a function like this
循环遍历数组并将每个项目与第二个数组中的项目进行比较。如果存在,则返回true。否则是假的。我会把它包装在这样的函数中
public bool IsPresentInArray(int[] firstArray, int[] secondArray)
{
foreach (var itemA in firstArray)
{
foreach (var itemB in secondArray)
{
if (itemB == itemA)
{
return true;
}
}
}
return false;
}
Now i can call it like this
现在我可以这样称呼它
int[] a = new int[]{1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8};
bool present= IsPresentInArray(a, b);
Read about foreach loop here
回答by Guffa
To efficiently compare all elements in one set to another, you can make a HashSetof one of them. Also, you can exit out of the loop as soon as you find the first match:
为了有效地将一组中的所有元素与另一组进行比较,您可以对其中HashSet的一个进行 a 。此外,您可以在找到第一个匹配项后立即退出循环:
HashSet<int> h = new HashSet<int>(a);
foreach (int i in b) {
if (h.Contains(i)) {
hasDuplicate = true;
break;
}
}
This is an O(n+m) solution, compared to having two nested loops comparing all values which is an O(n*m) solution.
这是一个 O(n+m) 解决方案,与具有两个嵌套循环比较所有值的 O(n*m) 解决方案相比。
回答by vapcguy
I used an "IndexOf" and "foreach" loop to create this. (Note: the first 3 "string" lines are just an example of how you could create an array and get it into the proper format).
我使用了“IndexOf”和“foreach”循环来创建它。(注意:前 3 个“字符串”行只是如何创建数组并将其转换为正确格式的示例)。
If you want to compare 2 arrays, they will be semi-colon delimited, but the last value won't have one after it. If you append a semi-colon to the string form of the array (i.e. a;b;c becomes a;b;c;), you can match using "x;" no matter what position it is in:
如果要比较 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) {
// ....
}
回答by The Kingmaker
Why don't we try to use LINQ? Check out the following code,
我们为什么不尝试使用 LINQ?看看下面的代码,
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;
}
回答by Marko Kekic
I did it with forloop. The point is that we compare each member to members from array b. So a[0]is compared to every member in the array bfirst and then it goes to a[1]and does the same thing, and so on, until it finds a match.
我是用for循环做的。关键是我们将每个成员与 array 中的成员进行比较b。So首先与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;
}
}
}

