我使用此代码获取列表框中的项目索引:
string searchfor = "B";
for (int i = 0; i < listBox1.Items.Count; i++)
{
listBox1.SelectedIndex = i;
if (searchfor == listBox1.Text)
Console.WriteLine(listBox1.SelectedIndex);
}
列出项目:
A
B => 1
F
E
R
B => 5
Y
B => 7
G
B => 8
任何人都可以帮我用linq做这件事吗?
答案 0 :(得分:4)
您可以使用包含项目索引的Select
重载:
listBox1.Items
.Select((item, index) => new {item, index})
.Where(ix => ix.item == searchFor)
.Select(ix => ix.index);
答案 1 :(得分:0)
string searchfor = "B";
var Items = listbox1.Items.Where( item => item.Text == searchfor);
//in case there are more than 1
Items.ForEach( i => Console.WriteLine(i.SelectedIndex))
或
string searchfor = "B";
var Item = listbox1.Items.FirstOrDefault( item => item.Text == searchfor);
Console.WriteLine(Item.SelectedIndex);
答案 2 :(得分:0)
这也应该有效:
listBox1.Items.Where(item=> item.Text == searchfor)
.ForEach(i => Console.WriteLine(listBox1.Items.IndexOf(i)));