List.BinarySearch Windows Phone
本文关键字:Phone Windows BinarySearch List | 更新日期: 2023-09-27 17:50:14
我在列表中搜索已经排序的数据,像这样:
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();
它工作得很慢。我认为需要使用列表。BinarySearch,但我不明白如何使用它为我的例子。
我试图实现一些东西,但它不工作。
由于compare是基于单词的,所以您可以使用输入单词创建新实例并将其传递给BinarySearch方法:
List<ShortWord> words;
int index = words.BinarySearch(new ShortWord() {
Word = text,
};
if (index >= 0) {
ShortWord result = words[index];
}
根据MSDN, BinarySearch将使用实现的IComparable。CompareTo方法:
编辑:此方法使用默认比较器comparer。类型T的默认值确定列表元素的顺序。比较器。默认的属性检查类型T是否实现了icomable泛型接口并使用该实现(如果可用)。如果不是这样,比较器。Default检查类型T是否实现IComparable接口。如果类型T没有实现任何接口,比较器。Default抛出InvalidOperationException。
如果列表中可能有多个具有相同单词的项,则应从索引开始迭代列表,直到得到具有不同单词的项。