替换列表中的字符串值 [英] Replace string values in list
问题描述
我有一个字符串集合,其中包含"goalXXvalue,goalXXLength,TestXX"之类的值.这是一个列表(字符串) 我以为我可以遍历每个项目并用下面的方法替换我尝试过的XX值,但是这些值不会改变.我要去哪里错了? 谢谢
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"))
metricList.ForEach(Function(n) n.Replace("XX", "1"))
推荐答案
您在这里遇到一些问题:
You have a few issues here:
- 首先,字符串是不可变的,因此,当您调用
.Replace
时,您将返回一个新字符串.调用n.Replace
不会修改n
. - 在匿名函数中分配给
n
不会影响列表中的值. - 无论如何,枚举时都不能更改集合的内容,因为它将使枚举无效.
- first, strings are immutable, so when you call
.Replace
you return a new string. Callingn.Replace
doesn't modifyn
. - 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.
由于似乎您要更改列表中的每个字符串,因此似乎无需尝试就地修改集合.因此,简洁的解决方案是使用Linq创建一个新列表:
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();
这篇关于替换列表中的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!