Home > Software design >  Problem replacing string within a list thats is attribute to an object within a loop
Problem replacing string within a list thats is attribute to an object within a loop

Time:10-13

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

CodePudding user response:

Just replace the whole list.

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

CodePudding user response:

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  )
{  
    ....
}
  •  Tags:  
  • c#
  • Related