Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a list in C#

Tags:

arrays

c#

search

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" }?
like image 410
Bob Avatar asked Aug 10 '10 09:08

Bob


People also ask

Is there a list in C?

The C Standard does not provide data structures like linked list and stack. Some compiler implementations might provide their own versions but their usage will be non portable across different compilers.

How do you search for a target key in a linked list?

To find the target key in a linked list, you have to apply sequential search. Each node is traversed and compared with the target key, and if it is different, then it follows the link to the next node. This traversal continues until either the target key is found or if the last node is reached.


2 Answers

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.

like image 81
Ani Avatar answered Nov 11 '22 01:11

Ani


// 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;
}
like image 28
Graviton Avatar answered Nov 11 '22 03:11

Graviton