我正在使用 C# WPF 开发 Windows 应用程序。 应用需要一个类如下
public class Limits
{
public String col1
{
get;
set;
}
public String col2
{
get;
set;
}
public String col3
{
get;
set;
}
}
我正在使用列表来存储对象,例如:-
List myList<Limits> = new List<Limits>();
“myList”有大约 15000 个对象。
现在,我想在这个 myList 中搜索特定属性。 例如:我想找出将 col1 设置为“abc”的对象。
如何使用二分搜索来解决这个问题?
最佳答案
首先,必须根据 col1
属性对列表进行排序,这样您才能完全使用二进制搜索。
您需要一个比较器来比较 col1
属性:
public class LimitsComparer : IComparer<Limits> {
public int Compare(Limits x, Limits y) {
return x.col1.CompareTo(y.col1);
}
}
然后你可以用它来进行二分查找:
int index = myList.BinarySearch(new Limits { col1 = "abc" }, new LimitsComparer());
返回的索引是:
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.
您还可以使用 Where
方法获取具有该属性的对象:
List<Limits> result = myList.Where(x => x.col1 == "abc").ToList();
虽然这不是那么有效,但您仍然应该考虑这是否是更好的解决方案,因为它更容易实现并提供更容易处理的结果。此外(这可能更重要),即使列表未按 col1
排序,它也能正常工作。
关于c# - 在 C# 中使用列表进行二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31888134/