C# WinForms ListBox 增量搜索 Key/Value 对作为 ListItems

C# WinForms ListBox Incremental Search with Key/Value Pairs as ListItems

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

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;
}

使用这个,我假设您要搜索的是 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>))

进行检查