Monday, January 17, 2011

Best overloaded function for arrayList.IndexOF

This is the best function which you can use for IndexOf Functionality . it provides lots of extra functionality.

  public int ArrayIndexOf(string[] arr, string search, int startIndex, bool caseSensitive, bool exactMatch)
    {
        // if the search is case-sensitive and it runs against exact matches only,
        //  use the standard Array.IndexOf function
        if (caseSensitive & exactMatch)
        {
            return Array.IndexOf(arr, search, startIndex);
        }

        if (!caseSensitive)
            search = search.ToLower();

        int lastIndex = arr.GetUpperBound(0);
        int i = 0;
        for (i = startIndex; i <= lastIndex; i++)
        {
            string currElem = arr[i];
            // if the search is not case-sensitive, convert everything to lower-case
            if (!caseSensitive)
                currElem = currElem.ToLower();
            if (exactMatch)
            {
                if (search == currElem)
                    return i;
            }
            else
            {
                // if partial matches are ok, use the String.IndexOf function,
                //  and return the
                // current index if a partial match is found
                int j = currElem.IndexOf(search);
                if (j > -1)
                    return i;
            }
        }

        // if we get here, no element matches the search options, so return -1
        return -1;
    }

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates