2014-04-29 47 views
0

我使用此代碼來獲得項目索引列表框在ListBox中項指標:LINQ - 查找

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辦呢?

+1

ListBox和控制檯在一個方法?有趣 –

回答

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); 
4

您可以使用Select過載,其中包括該項目的指數:

listBox1.Items 
     .Select((item, index) => new {item, index}) 
     .Where(ix => ix.item == searchFor) 
     .Select(ix => ix.index); 
0

這應該工作以及:

listBox1.Items.Where(item=> item.Text == searchfor) 
     .ForEach(i => Console.WriteLine(listBox1.Items.IndexOf(i)));