以键/值对作为ListItems的C#WinForms ListBox增量搜索

本文关键字:ListBox C#WinForms 搜索 ListItems 以键 | 更新日期: 2023-09-27 18:00:09

我已经搜索了一个答案,虽然有一个在使用字符串类型项目的列表框时有效,但当我的项目是类型时,我不知道如何转换

KeyValuePair<string, ChangeRec>

我希望能够在列表框中键入时进行搜索(不能使用组合框,因为控件需要在表单上具有特定大小),按键(文本)项进行搜索。感谢@Marcel Popescu的首发。这是我的代码版本(只在失败的行上方进行了注释,因为它不能将kvp项强制转换为字符串):

private string searchString;
private DateTime lastKeyPressTime;
private void lbElementNames_KeyPress(object sender, KeyPressEventArgs e)
{
    this.IncrementalSearch(e.KeyChar);
    e.Handled = true;
}
private void IncrementalSearch(char ch)
{
    if ((DateTime.Now - this.lastKeyPressTime) > new TimeSpan(0, 0, 1))
    {
        this.searchString = ch.ToString();
    }
    else
    {
        this.searchString += ch;
    }
    this.lastKeyPressTime = DateTime.Now;
    //* code falls over HERE *//
    var item =
        this.lbElementNames.Items.Cast<string>()
            .FirstOrDefault(it => it.StartsWith(this.searchString, true, CultureInfo.InvariantCulture));
    if (item == null) return;
    var index = this.lbElementNames.Items.IndexOf(item);
    if (index < 0) return;        
    this.lbElementNames.SelectedIndex = index;
}

以键/值对作为ListItems的C#WinForms ListBox增量搜索

使用此选项,我假设您要在其中搜索的是KeyValuePairKey

//* code falls over HERE *//
var item =
        this.lbElementNames.Items.Cast<KeyValuePair<string, ChangeRec>>()
            .FirstOrDefault(it => it.Key.StartsWith(this.searchString, true, CultureInfo.InvariantCulture));
if (item.Equals(default(KeyValuePair<string, ChangeRec>))) return;

由于KeyValuePair是一种值类型,因此它永远不能为null。为了查明它是否被分配了一个值,我们使用item.Equals(default(KeyValuePair<string, ChangeRec>))

进行检查
相关文章: