Bob
Bob

Reputation: 243

How to search a list in C#

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" }?

Upvotes: 6

Views: 369

Answers (2)

Ani
Ani

Reputation: 113402

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.

Upvotes: 10

Graviton
Graviton

Reputation: 83254

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

Upvotes: 1

Related Questions