C# 在带有键的组合框中选择KeyValuePair
我在combobx中有几个KeyValuePairC# 在带有键的组合框中选择KeyValuePair,c#,combobox,keyvaluepair,C#,Combobox,Keyvaluepair,我在combobx中有几个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")); 我认为您可以像这样使用LINQ: this.cbEndQtr.SelectedItem =
this.cbEndQtr.Items.Clear();
this.cbEndQtr.Items.Add(new KeyValuePair<int, string>(1, "Test1"));
this.cbEndQtr.Items.Add(new KeyValuePair<int, string>(2, "Test2"));
我认为您可以像这样使用LINQ:
this.cbEndQtr.SelectedItem = 2;
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;
我认为您可以像这样使用LINQ:
this.cbEndQtr.SelectedItem = 2;
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;
以下是一种暴力方法:
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);
我发现了这一条线的方法:
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);
尽管如果找不到匹配项,一切都不会改变。这里有一个暴力方法:
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);
我发现了这一条线的方法:
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);
虽然如果找不到匹配项,则不会有任何更改。for循环中不会有任何更改,但如果找不到,则“一行”方法会将所选项目设置为null。@Silvermind KeyValuePair不可为null,因此您最终尝试将SelectedItem设置为KeyValuePair的新实例的默认值。在我的快速测试中,如果已经选择了某个项目,它将保持选中状态。我的错误,没有注意到。for循环中不会有任何更改,但是如果没有找到,您的“一行”方法会将所选项目设置为null。@Silvermind KeyValuePair不可为null,因此您最终尝试将SelectedItem设置为KeyValuePair的新实例的默认值。在我的快速测试中,如果某个东西已经被选中,它将保持选中状态。我的坏朋友,没有注意到这一点。