Array.IndexOf vs. 给定索引问题的值



我正在尝试遍历给定的数组并查找其中有多少个重复值。它的工作原理是通过嵌套循环检查数组的所有元素,并确保如果它位于同一索引上,它不会上升计数器。但问题是,它永远不会计数! 现在要么我不明白 valueOf vs indexOf 的概念,要么我完全迷失了。

int[] myArr = new int[] { 10, 5, 5 };
int counter = 0;
for (int i = 0; i < myArr.Length; i++)
{
for (int j = 0; j < myArr.Length; j++)
{
if (Array.IndexOf(myArr, myArr[i]) == Array.IndexOf(myArr, myArr[j]))
{
continue;
}
else if (myArr[i] == myArr[j])
{
counter++;
}
}
}
Console.WriteLine("There are {0} repeating values in the array.", counter); 

// Output: There are 0 repeating values in the array.

Array.IndexOf 搜索数组中第一个出现的值。

看起来在您的示例中,您正在尝试使用它来确保您没有比较数组中的相同位置。在这种情况下,您可以将该条件替换为if(i == j)

与其他答案/注释一起说明Array.IndexOf不是解决此问题的正确方法,并且不确定是否允许您使用 LINQ,但这是迄今为止更好的方法,尤其是使用GroupBy方法。

我为您创建了一个点小提琴来显示我在做什么。

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
int[] myArr = new int[] { 10, 5, 5, 3, 3, 3 };
// int counter = 0; - now this is no longer needed
var numbersThatAreDuplicates = myArr.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => new { number = x.Key, countOfNumber = x.Count()}).ToList();
Console.WriteLine("There are {0} repeating values in the array.", numbersThatAreDuplicates.Count);
foreach (var item in numbersThatAreDuplicates)
{
Console.WriteLine(item.number + " repeats itself " + item.countOfNumber + " times.");
} 
}
}
// Output
// There are 2 repeating values in the array.
// 5 repeats itself 2 times.
// 3 repeats itself 3 times.

如您所见,通过GroupBy方法,您可以找出有多少数字在重复,以及实际数字以及实际数字在 1 行代码中重复的出现次数。 比使用循环嵌套更干净、更高效,但我再次不确定您的局限性是什么。

我希望这有所帮助。

您不需要使用Array.IndexOf()函数。

例如:

int[] myArr = new int[] { 10, 5, 5, 5};
int counter = 0;
List<int> dups = new List<int>();
for (int i = 0; i < myArr.Length; i++)
{
for (int j = 0; j < myArr.Length; j++)
{
if (i != j && myArr[i] == myArr[j] && !dups.Contains(i))
{
dups.Add(j);
counter++;
}
}
}
Console.WriteLine("There are {0} repeating values in the array.", counter);

// Output: There are 2 repeating values in the array.

最新更新