如何获取包含字符串的列表的索引

a12*_*773 3 c# list winforms

我有一个List<string>,我检查它是否包含一个字符串:

if(list.Contains(tbItem.Text))
Run Code Online (Sandbox Code Playgroud)

如果这是真的,我这样做:

int idx = list.IndexOf(tbItem.Text)
Run Code Online (Sandbox Code Playgroud)

但是,如果我有两个相同的字符串怎么办?我想获得具有此字符串的所有索引,然后使用foreach循环遍历它.我怎么能这样做?

Tim*_*ter 13

假设列表List<string>:

IEnumerable<int> allIndices = list.Select((s, i) => new { Str = s, Index = i })
    .Where(x => x.Str == tbItem.Text)
    .Select(x => x.Index);

foreach(int matchingIndex in allIndices)
{
    // ....
}
Run Code Online (Sandbox Code Playgroud)