List.BinarySearch Windows Phone

List.BinarySearch Windows Phone

我在我的列表中搜索已经排序的数据,如下所示:

public class ShortWord: IComparable<ShortWord>
{
    public int id { get; set; }
    public string Word { get; set; }

    public int CompareTo(ShortWord obj)
    {
       return this.Word.CompareTo(obj.Word);
    }
}

List<ShortWord> words;
words.Where(t => t.Word.IndexOf(text.ToUpper()) == 0).Take(30).ToList();

运行速度非常慢。我认为需要使用 List.BinarySearch,但我不明白如何在我的示例中使用它。

我正在尝试实现一些东西,但它不起作用。

由于比较是基于单词的,你可以用输入的单词创建新的实例并将其传递给BinarySearch方法:

List<ShortWord> words;
int index = words.BinarySearch(new ShortWord() {
     Word = text,
};
if (index >= 0) {
  ShortWord result = words[index];
}

根据 MSDN,BinarySearch 将使用实现的 IComparable.CompareTo 方法:

This method uses the default comparer Comparer.Default for type T to determine the order of list elements. The Comparer.Default property checks whether type T implements the IComparable generic interface and uses that implementation, if available. If not, Comparer.Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer.Default throws an InvalidOperationException.

编辑:

如果列表中可能有多个项目具有相同的词,则应从索引开始迭代列表,直到获得具有不同词的项目。