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"))
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
There are three ways to replace an item in a Python list. You can use list indexing or a for loop to replace an item. If you want to create a new list based on an existing list and make a change, you can use a list comprehension. You may decide that you want to change a value in a list.
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
You have a few issues here:
.Replace
you return a new string. Calling n.Replace
doesn't modify n
.n
in your anonymous function won't affect the value that's in your list.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();
Problem: You aren't doing anything with the Replaced strings.
You could easily do this, using a simple loop:
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...
Or using Linq:
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:
C#
using System.Linq;
VB.NET
Imports System.Linq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With