Why is the BinarySearch() function of List class (C#) always returning me a negative index?
I made a C# List containing 79244 words from a text file. There is an InputField and a Submit Button. When I type a word and press the Submit button, using the BinarySearch() function of the List class, the code shall display the index of that word in the list. Whenever, a word is found, the BinarySearch() function should return its positive index value, but in this case, it is always returning a negative number. Have I done something wrong? Please help. Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CheckDict : MonoBehaviour {
public InputField inpText;
public Text showText;
public TextAsset dictFile;
private string textToString;
private List<string> dictList;
private int dictLen;
void Start () {
dictList = TextToList (dictFile);
dictLen = dictList.Count;
showText.text = dictLen.ToString();
}
// function to extract each word in the textfile separated by a new line and adding it to the string
private List<string> TextToList (TextAsset ts) {
return new List<string> (ts.text.Split ('\n'));
}
public void OnSubmit () {
textToString = inpText.text.ToString();
int index = dictList.BinarySearch (textToString);
Debug.Log (index);
// if (dictList.BinarySearch (textToString) < 0)
// showText.text = "Word missing from dictionary";
// else
// showText.text = textToString;
}
}
Output:
Answer by JDKey · Dec 05, 2018 at 02:23 PM
Hey, I know you've probably solved this or moved on to another project, but for those who come to this post looking for BinarySearch() solutions, I noticed this in the official docs: "The zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."
I tried to figure out what this means so I could explain it, but after googling it and reading a few pages, my brain began to fuse and you know what a mess that makes! So I'll leave that to you or others to figure out. As for me, I'll search for other solutions that don't involve keyboard cleaning.
Your answer
Follow this Question
Related Questions
"error CS1501: No overload for method `Add' takes `2' arguments" 0 Answers
Char variable from list to string 0 Answers
How to check if gameobject has a tag, from a list. 1 Answer
Search multiple text files for string input by user 1 Answer
Search for specific type of objects inside the Hierarchy 1 Answer