How to add each item to a string list in C # using a Lambda expression

I found a version of VB here, but I would like to use a Lambda expression to take a list of strings, and then add a string to each item in the list.

It seems that using ForEach ends up sending the string by value, so any changes disappear. Here is a line of code that I was hoping to work on.

listOfStrings.ForEach((listItem) => {listItem = listItem.Insert(0,"a");});
+5
source share
4 answers

Lines are immutable; they cannot be changed "in place". Therefore, you will need to replace every entry in the list that you cannot do with List<T>.ForEach. At this point, you are best off creating a new list:

listOfStrings = listOfStrings.Select(value => "a" + value).ToList();
+16
source

, for.

for (int index = 0; index < list.Count; index++)
{
     list[index] = // modify away!
}

Select(Func<T, TOut> selector) .ToList() .ToArray(), .

+4
List<string> x = new List<string>();
            x.Add("d");

            List<string> res = x.Select(c => "a" + c).ToList();
+3
source

You can create your own extension:

public static void ForEachChange<T>(this List<T> List, Func<T, T> Func)
{
    for(int i = 0; i < List.Count; i++)
        List[i] = Func(List[i]);
}

listOfStrings.ForEachChange((listItem) => {return listItem.Insert(0,"a");});

will work now

Edit:
Now working

+1
source

All Articles