如何从上一个找到的项目的索引开始查找下一个项目?

时间:2016-02-15 12:12:25

标签: c#

我想在字符串列表中搜索字符串并获取其索引

List<string> list; 
int index;
private void button1_Click(object sender, EventArgs e)
{           
    index = list.FindIndex(x => x.Contains(textBox1.Text));
    if (index >= 0)
    {
        listView1.Items[index].Selected = true;
    }
}

现在,如果用户再次点击按钮,则索引应该是列表中下一次出现的搜索项目。如何从上一个索引index开始执行此操作?

1 个答案:

答案 0 :(得分:3)

您可以将overload of FindIndex与start-index:

一起使用
Mention how many numbers to be added
4
Enter 4 numbers
1 2 3 4
Sum of them = 10
4 10 1637156136366093893632.000000
Average = 1637156136366093893632.00 

或更短:

int index = -1;
private void button1_Click(object sender, EventArgs e)
{
    if (index == list.Count - 1)
        index = -1;
    if (index >= 0)
        index = list.FindIndex(index + 1, x => x.Contains(textBox1.Text));
    else
        index = list.FindIndex(x => x.Contains(textBox1.Text));
    if (index >= 0)
    {
        listView1.Items[index].Selected = true;
    }
}