2010-08-10 24 views
6

搜索列表我有一個列表如下所示:如何用C#

List<string[]> countryList 

和字符串數組的每個元素是另一陣列3層的元件。

所以countryList[0]可能包含數組:

new string[3] { "GB", "United Kingdom", "United Kingdom" }; 

如何搜索countryList特定陣列例如如何搜索countryList

new string[3] { "GB", "United Kingdom", "United Kingdom" }? 

回答

10
return countryList.FirstOrDefault(array => array.SequenceEqual(arrayToCompare)); 

要簡單地建立的存在,使用countryList.Any。 若要查找元素的索引或-1(如果不存在),請使用countryList.FindIndex

+0

我是否缺少一些東西,因爲我沒有FirstOrDefault方法在我的清單對象中,我有一個Find和FindAll。我沒有SequenceEqual。我正在使用.NET 3.5 – Bob 2010-08-10 10:59:47

+0

啊,我沒有system.linq導入... ups! – Bob 2010-08-10 11:11:31

1
// this returns the index for the matched array, if no suitable array found, return -1 

public static intFindIndex(List<string[]> allString, string[] string) 
{ 
    return allString.FindIndex(pt=>IsStringEqual(pt, string)); 
} 


private static bool IsStringEqual(string[] str1, string[] str2) 
{ 
    if(str1.Length!=str2.Length) 
     return false; 
    // do element by element comparison here 
    for(int i=0; i< str1.Length; i++) 
    { 
     if(str1[i]!=str2[i]) 
     return false; 
    } 
    return true; 
} 
+0

錯誤... Equals方法比較引用而不是數組內的值,所以它不會找到任何東西。 – 2010-08-10 10:04:15

+0

!LukaszW.pl,我已經更新了答案 – Graviton 2010-08-10 10:05:38

+0

現在更好;) – 2010-08-10 10:07:10