2016-04-17 30 views
0

我有一個數據數組,我知道它只包含我正在搜索的一個值,但我想知道數組中哪個位置的值所以我可以在另一個數組中找到相應的數據。如何在c#中找到一個數組中項目的位置

像這樣的事情

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; 
    } 
} 

這當然看起來似乎會很容易做到的,但我似乎無法找到如何。

任何幫助,這是非常感謝。

+0

這裏是C#中的數組引用:https://開頭MSDN .microsoft.com/EN-US /庫/ system.array.aspx。你想要「IndexOf」 – Tibrogargan

回答

3

只要做

result = i; 

i是陣列中的位置。

1

您可能要優化你的代碼執行此操作時:

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 
    } 
} 
1

簡短的方式是使用Array.IndexOf方法:

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