简体   繁体   English

替换列表中的字符串值

[英]Replace string values in list

I have a collection of strings which contain values like "goalXXvalue,goalXXLength,TestXX".我有一个字符串集合,其中包含诸如“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.这是一个 List(of String) 我以为我可以遍历每个项目并替换我用下面的方法尝试过的 XX 值,但这些值不会改变。 Where am I going wrong?我哪里错了? Thanks谢谢

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

You have a few issues here:你在这里有几个问题:

  • first, strings are immutable, so when you call .Replace you return a new string.首先,字符串是不可变的,所以当你调用.Replace你会返回一个新的字符串。 Calling n.Replace doesn't modify n .调用n.Replace不会修改n
  • assigning to n in your anonymous function won't affect the value that's in your list.在匿名函数中分配给n不会影响列表中的值。
  • 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:因此,简洁的解决方案是使用 Linq 来创建一个新列表:

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

Problem: You aren't doing anything with the Replaced strings.问题:您没有对已替换的字符串执行任何操作。
You could easily do this, using a simple loop:你可以很容易地做到这一点,使用一个简单的循环:

C# C#

for(int i = 0; i < metricList.Count; i++)
{
    metricList[i] = metricList[i].Replace("XX", "1");
}

VB.NET网络

For i As Integer = 0 To metricList.Count - 1
    metricList(i) = metricList(i).Replace("XX", "1")
Next

Code iterates through all strings in metricList and replaces XX for 1 , it then stores the values back at the correct place in the list, what you aren't doing in your code...代码遍历metricList所有字符串并将XX替换为1 ,然后将值存储回列表中的正确位置,您在代码中没有做什么...

Or using Linq:或者使用 Linq:

C# C#

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

VB.NET网络

Dim newList = metricList.Select(Function(x) x.Replace("XX", "1")).ToList()

Don't forget to add a reference to linq at the top of your class:不要忘记在类的顶部添加对 linq 的引用:

C# C#

using System.Linq;

VB.NET网络

Imports System.Linq

You need to assign result of String.Replace method.您需要分配 String.Replace 方法的结果。 So your func should return something or use instead of foreach select所以你的 func 应该返回一些东西或者使用而不是 foreach select

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM