1

我在一个组合中有几个 KeyValuePair。

this.cbEndQtr.Items.Clear();
this.cbEndQtr.Items.Add(new KeyValuePair<int, string>(1, "Test1"));
this.cbEndQtr.Items.Add(new KeyValuePair<int, string>(2, "Test2"));

通过传入键来选择的最简单方法是什么。例如这样的:

this.cbEndQtr.SelectedItem = 2;
4

2 回答 2

4

这是一种蛮力方法:

void selectByKey(int key)
{
    foreach (var item in cbEndQtr.Items)
        if (((KeyValuePair<int, string>)item).Key == key) 
        {
            cbEndQtr.SelectedItem = item;
            break;
        }
}

我刚刚发现了这种单行方法:

cbEndQtr.SelectedItem = cbEndQtr.Items.OfType<KeyValuePair<int, string>>().ToList().FirstOrDefault(i => i.Key == key);

尽管如果找不到匹配项,则什么都不会改变。

于 2014-02-28T22:57:10.763 回答
3

我认为你可以LINQ这样使用:

var key = 2; // get key from somewhere

var items = this.cbEndQtr.Items.OfType<KeyValuePair<int, string>>()
             .Select((item,index) => new { item, index);

var index = items.Where(x => x.item.Key == key).Select(x => x.index).First();        

this.cbEndQtr.SelectedIndex = index;
于 2014-02-28T22:56:06.610 回答