a1204773
a1204773

Reputation: 7043

How to get the indexes of list that contains a string

I have a List<string> and i check if it contains a string:

if(list.Contains(tbItem.Text))

and if it's true I do this:

int idx = list.IndexOf(tbItem.Text)

But what if I have for example 2 same strings? I want to get all the indexes that have this string and then use foreach to loop through it. How I can do that?

Upvotes: 6

Views: 13183

Answers (2)

MarcF
MarcF

Reputation: 3299

How about this:

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

or get the indexes using linq

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

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460038

Assuming list is a 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)
{
    // ....
}

Upvotes: 15

Related Questions