如何在c#中的数组中查找项的位置

本文关键字:查找 位置 数组 | 更新日期: 2024-09-25 12:55:43

我有一个数据数组,我知道它只包含我正在搜索的值之一,但我想知道该值在数组中的哪个位置,这样我就可以在另一个数组中找到相应的数据。

像这样的

int[] data = new int[] { 2, 7, 4, 9, 1 };
int search = 4;
int result;
for (int i = 0; i < data.Length; i++)
{
    if (data[i] == search)
    {
        result = data[i].Position;
    } 
}

这看起来确实很容易做到,但我似乎不知道该怎么做。

如有任何帮助,我们将不胜感激。

如何在c#中的数组中查找项的位置

只需进行

result = i;

i是数组中的位置。

简单的方法是使用Array.IndexOf方法:

int[] data = new int[] { 2, 7, 4, 9, 1 };
int search = 4;
int index = Array.IndexOf(data, search);

执行此操作时,您可能需要优化代码:

int[] data = new int[] { 2, 7, 4, 9, 1 };
int search = 4;
int result;
for (int i = 0; i < data.Length; i++)
{
   if (data[i] == search)
   {
       result = i;
       break; //This will exit the loop after the first match
              //If you do not do this, you will find the last match
   } 
}