c# - 在 C# 中使用列表进行二进制搜索

标签 c# algorithm list binary-search

我正在使用 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/

相关文章:

c# - 关于 .NET 的 2 个基本但有趣的问题

c# - 使用 'Same Name' 属性实现 2 个接口(interface)

c++ - 数字对的有效搜索

python - 我的搜索词只打印列表中的最后一个词而不是找到的词 [Python 2.7.6]

c# - 关闭 WPF GUI 应用程序的正确方法 : GetCurrentProcess(). Kill()、Environment.Exit(0) 或 this.Shutdown()

c# - 使用 Moq 设置事件聚合器事件

c - 在 O(logn) 时间内求出从 k= 0 到 n 的 x^k 的总和

algorithm - 如何在线性时间内计算列表中的不同值?

java - 克隆/复制不可修改的列表

任何类型函数的 C++ 列表或 vector