Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c# - Replace string values in list

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

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

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...