kPuck
kPuck

Reputation: 147

Problem replacing string within a list thats is attribute to an object within a loop

I have a class Plott. One of the attributes is a list with header names called Headers. The list stores the names of all the columns within the plot.

I need to loop through these objects (plt which are in a List) and find any occurrences of headers containing the string "aaa" and replace it with the string "bbb".

I successfully loop through and find these headers within these objects. I can also define a new string which replaces "aaa" with "bbb" but when I try to assignee the new string i.e that index of the List to that object it gives an error regarding that the set has changed and the loop can't continue (the error message is not in English so I wont post it here)

foreach (Plott obj in plt) {
    int c = 0;
    foreach (String s in obj.Headers)
    { 
        if (s.Contains("aaa"))
        {
            string newstr;
            newstr = s.Replace("aaa", "bbb");
            obj.Headers[c] = newstr;
        }
        c++;
    }
}

Upvotes: 0

Views: 58

Answers (2)

John Wu
John Wu

Reputation: 52210

Just replace the whole list.

obj.Headers = obj.Headers.Select( x => x.Replace("aaa","bbb") ).ToList();

Upvotes: 3

jason.kaisersmith
jason.kaisersmith

Reputation: 9610

The variable you retrieve in a foreach loop is a readonly copy of the element in the collection, so you can't modify it.

If you want to do this then you need to use a simple for loop

for (int ind = 0; ind < plt.Count(); ind++)
{  
    ....
}

Upvotes: 1

Related Questions