4

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

if(list.Contains(tbItem.Text))

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

int idx = list.IndexOf(tbItem.Text)

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

4

2 回答 2

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)
{
    // ....
}
于 2013-03-09T00:04:51.200 回答
1

这个怎么样:

List<int> matchingIndexes = new List<int>();
for(int i=0; i<list.Count; i++)
{
    if (item == tbItem.Text)
        matchingIndexes.Add(i);
}

//Now iterate over the matches
foreach(int index in matchingIndexes)
{
    list[index] = "newString";
}

或使用 linq 获取索引

int[] matchingIndexes = (from current in list.Select((value, index) => new { value, index }) where current.value == tbItem.Text select current.index).ToArray();
于 2013-03-09T00:03:08.113 回答