Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a collection of strings which contain values like "goalXXvalue,goalXXLength,TestXX". It is a List(of String) I thought I would be able to loop through each item and replace the XX value which I've tried with the method below but the values don't change. Where am I going wrong? Thanks

metricList.ForEach(Function(n) n.Replace("XX", "1"))

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have a few issues here:

  • first, strings are immutable, so when you call .Replace you return a new string. Calling n.Replace doesn't modify n.
  • assigning to n in your anonymous function won't affect the value that's in your list.
  • regardless of the above, you can't change the content of your collection while enumerating it, because it'll invalidate the enumeration.

Since it seems you're changing every string in your list, it seems unnecessary to try to modify the collection in-place. Therefore, the succint solution would be to use Linq would to create a new list:

var newList = metricList.Select(s => s.Replace("XX", "1")).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...