Costa Brava Cycling Party May 2010

Thursday, December 07, 2006

Quickly check if elements exist in an array with c#

With Array.BinarySearch you can quickly see if an element is already in an array. But make sure you Sort the array first, otherwise you get unexpected results! The algorithm used in BinarySearch assumes you have sorted the array.

Example :

string[] strArray = new string[4];
strArray[0] = "cmg";
strArray[1] = "ordina";
strArray[2] = "getronicspinkroccade";
strArray[3] = "infosupport";
Array.Sort(strArray);
int v = Array.BinarySearch(strArray, "infosupport");
if (v > 0)
{
//element found
}


Make sure you trimmed/uppercase/lowercased the items, because the binarysearch only finds the element if it is exactly the same.

source :
http://aspnet.4guysfromrolla.com/articles/110602-1.aspx

No comments: