2013-03-08 4 views
3

문자열을 포함 목록의 인덱스를 얻을 내가 그것을 문자열이 포함되어 있는지 확인하는 방법 :나는 <code>List<string></code>이

if(list.Contains(tbItem.Text)) 

를하고 사실이라면 내가 할이 :

int idx = list.IndexOf(tbItem.Text) 

그러나 예를 들어 2 개의 동일한 문자열이 있다면 어떻게됩니까? 이 문자열을 가지고있는 모든 인덱스를 얻고 foreach를 사용하여 루프를 돌리고 싶습니다. 내가 어떻게 할 수 있니?

+0

목록은 무엇인가? 그것은 목록입니까? 예 목록 kashif

+0

는 – a1204773

+0

@kashif – kashif

답변

12

LINQ를 목록를 사용하여 인덱스를 얻을 수있는 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

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"; 
} 

또는 가정

int[] matchingIndexes = (from current in list.Select((value, index) => new { value, index }) where current.value == tbItem.Text select current.index).ToArray(); 
관련 문제