tags:

views:

130

answers:

2

Hi there,

I have a list like so:

List<string[]> countryList

and each element of the string array is another array with 3 elements.

So countryList[0] might contain the array:

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

How can I search countryList for a specific array e.g. how to search countryList for

new string[3] { "GB", "United Kingdom", "United Kingdom" }?
+1  A: 

// 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;
}
Ngu Soon Hui
Wrong... Equals method compares the references not the values inside of the array, so it will never find anything.
ŁukaszW.pl
!LukaszW.pl, I've already updated the answer
Ngu Soon Hui
Now it's better ;)
ŁukaszW.pl
+9  A: 
return countryList.FirstOrDefault(array => array.SequenceEqual(arrayToCompare));

To simply establish existence, use countryList.Any. To find the index of the element or -1 if it does not exist, use countryList.FindIndex.

Ani
Am i missing something as I don't have a FirstOrDefault method on my List<string[]> object, i have a Find and FindAll. And i don't have a SequenceEqual. I am using .NET 3.5
Bob
ah, i didn't have system.linq imported ... ups!
Bob