游戏有点晚了,但我找不到任何有用的东西,所以我想出了这个简单的解决方案:
comboBox1.Items.OfType<SomeType>().Any(x => x == YourValue)
或者:
comboBox1.Items.OfType<SomeType>().Any(x => x.SomeProperty == YourValue)
演示示例:
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
// ...
var people = new List<Person>() { /* Add some data */ };
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = people;
// ...
bool exists = comboBox1.Items.OfType<Person>().Any(p => p.Id == 1);
或者,如果您需要获取项目的索引,您可以使用以下内容:
var person = comboBox1.Items.OfType<Person>().FirstOrDefault(p => p.Id == 1);
var index = (person != null) ? comboBox1.Items.IndexOf(person) : -1;