2013-03-08 59 views
3

我有一个List<string>索引和我检查它是否包含一个字符串:如何获取列表包含字符串

if(list.Contains(tbItem.Text)) 

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

int idx = list.IndexOf(tbItem.Text) 

但如果我有例如2个相同的字符串呢?我想获得所有包含这个字符串的索引,然后使用foreach循环它。我该怎么做?

+0

是什么列表?是列表? – kashif 2013-03-09 00:01:09

+0

@ kashif是列表 a1204773 2013-03-09 00:01:38

+0

@loclip写完整的代码,你有 – kashif 2013-03-09 00:02:19

回答

12

假设列表拿到指标是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) 
{ 
    // .... 
} 
+0

谢谢你的工作很棒..我假设其他答案也可以工作,所以谢谢大家.. – a1204773 2013-03-09 00:10:05

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(); 
相关问题