0

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++;
    }
}
3
  • you're changing the list you are looping thru. the error message is spot on. Commented Oct 13, 2021 at 7:10
  • yes but I'm not changing the number of items in the list? I'm just altering an entry. Commented Oct 13, 2021 at 7:12
  • 'just' altering thing being looped thru...find another way - hint: -grab the indexes for items being changed first Commented Oct 13, 2021 at 7:14

2 Answers 2

3

Just replace the whole list.

obj.Headers = obj.Headers.Select( x => x.Replace("aaa","bbb") ).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

This will only work if obj.Headers has a public setter
1

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++)
{  
    ....
}

2 Comments

Thank you! I didn't know. Now I wont make this mistake again.
Note that only the inner loop over Headers needs to be changed to a for loop the outer loop over plt can still be a foreach loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.