2010-08-10 7 views
6

J'ai une liste comme ceci:Comment rechercher une liste en C#

List<string[]> countryList 

et chaque élément du tableau de chaînes est un autre tableau avec 3 éléments.

Ainsi countryList[0] peut contenir le tableau:

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

Comment puis-je rechercher countryList pour un tableau spécifique par exemple comment rechercher countryList pour

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

Répondre

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

simplement établir l'existence, utilisez countryList.Any. Pour trouver l'index de l'élément ou -1 s'il n'existe pas, utilisez countryList.FindIndex.

+0

Ai-je manquant quelque chose que je n'ai pas une méthode FirstOrDefault sur mon objet Liste , j'ai un Find et FindAll. Et je n'ai pas de SequenceEqual. J'utilise. NET 3.5 – Bob

+0

ah, je n'ai pas eu system.linq importé ... ups! – Bob

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

Wrong ... La méthode Equals compare les références et non les valeurs à l'intérieur du tableau, de sorte qu'il ne trouvera jamais rien. –

+0

! LukaszW.pl, j'ai déjà mis à jour la réponse – Graviton

+0

Maintenant c'est mieux;) –

Questions connexes