Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prepend every item in a list of strings in C# with a Lambda Expression

Tags:

c#

lambda

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");});
like image 510
Jonathan Beerhalter Avatar asked Jun 08 '11 03:06

Jonathan Beerhalter


People also ask

How do I append to a string list?

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.

How do you concatenate a string with each element in a list Python?

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.

How do you add a string to the end of a string in Python?

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.


2 Answers

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();
like image 200
user7116 Avatar answered Oct 20 '22 13:10

user7116


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.

like image 44
Anthony Pegram Avatar answered Oct 20 '22 12:10

Anthony Pegram