How to add value to each item in array inline style

Lets say I have an array

string[] arr = new string[] {"1","2","3"};

I would like to add a string to the end of value, something like this:

arr.appendToEnd(" Test");

return arr; // returns {"1 Test","2 Test","3 Test"}

I was wondering if there is something built-in that can do this, rather than having to build my own extension method.

Jon Skeet
people
quotationmark

There isn't anything built-in. You could use LINQ to create a new array easily:

arr = arr.Select(x => x + " Test").ToArray();

... but that's not going to modify the original array. If anything else has a reference to the original array, they won't see the change. Usually that's actually a good thing IMO, but occasionally you might want to modify the existing collection.

For that, you could write your own general purpose method to modify an existing array (or any other IList<T> implementation):

public static void ModifyAll<T>(this IList<T> source, Func<T, T> modification)
{
    // TODO: Argument validation
    for (int i = 0; i < source.Count; i++)
    {
        source[i] = modification(source[i]);
    }
}

Then you could use:

arr.ModifyAll(x => x + " Test");

I would definitely use this rather than writing a string-concatenation-specific extension method.

people

See more on this question at Stackoverflow