c# 二进制搜索方法“未处理的异常:System.IndexOutOfRangeException:”

c# binary search method " Unhandled Exception: System.IndexOutOfRangeException:"

无法将此二进制搜索结果转换为 int。到目前为止,所有代码都运行良好。我想输入一个名称并显示 json 实例化中的内容。我已经排序了。谢谢

"Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array."

 static void SearchEntity(Entity[] entities)
    {
            Entities result = new Entities();
            Console.WriteLine("Which name to find ");
            string userInput = Console.ReadLine();
            string[] title = new string[10000];

 //-------------
            Console.Write("Search Keyword : ");
            string searchKeyword = Console.ReadLine();
            if (userInput.ToLower() == "title")
            {
               title = entities.Select(m => m.Title).ToArray();

                Array.Sort(title);
                Sorting.Sort(entities, userInput);                                                 

                var tmp = Array.BinarySearch<string>(title, userInput);



                if (Convert.ToInt32(tmp) == -1)
                {
                    Console.WriteLine("No data found!");
                    return;
                }
                result = entities[Convert.ToInt32(tmp)];
                entitiesPrint(result);
            }

来自 Array.BinarySearch 文档:

The index of the specified value in the specified array, if value is found; otherwise, a negative number. If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

如果找不到确切的值,该方法可以 return 各种负数,而不仅仅是 -1。您将要改用以下内容:

if (tmp < 0) 
    // ...

还值得注意的是 Array.BinarySearch return 已经是 int,因此对 Convert.ToInt32 的调用是多余的。