I found a VB version of this here, but I'd like to use a Lambda Expression to take a List of strings and then prepend a string onto every item in the list.
It seems like using the ForEach ends up sending in the string by value, so any changes disappear. Here's the line of code I was hoping to have work.
listOfStrings.ForEach((listItem) => {listItem = listItem.Insert(0,"a");});
We use the append() function to append a string item to the endpoint of the list without altering the string state to the characters list. The append() method inserts a particular value to the current list.
Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
Using += operator to append strings in Python The plus equal operator (+=) appends to strings and creates a new string while not changing the value of the original string.
Strings are immutable, they cannot be altered "in place". Therefore, you'd have to replace each entry in the list which you cannot do with List<T>.ForEach
. At this point you'd be best just making a new list:
listOfStrings = listOfStrings.Select(value => "a" + value).ToList();
If you need to modify the list in place, then an explicit for
loop is appropriate.
for (int index = 0; index < list.Count; index++)
{
list[index] = // modify away!
}
Otherwise, use the Select(Func<T, TOut> selector)
with the optional .ToList()
or .ToArray()
as demonstrated by sixlettervariables.
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