2010-08-10 39 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