1

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.

RealWorldCoder
  • 1,031
  • 1
  • 10
  • 16
  • just loop through the array and add to each element a space and test . i don't think there is a built in method. – Jean Raymond Daher Oct 08 '14 at 17:57
  • http://stackoverflow.com/questions/3867961/c-altering-values-for-every-item-in-an-array you could probably modify this to suit your needs – eddie_cat Oct 08 '14 at 17:58

2 Answers2

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hey, thanks. What is `arr` before you use `.ToArray()` ? (curious) – RealWorldCoder Oct 08 '14 at 18:01
  • 1
    @RealWorld: I'm not sure what you mean. `arr.Select(x => x + " Test")` returns a lazily-evaluated iterator which will yield the result of the projection when asked. It doesn't modify `arr` at all. – Jon Skeet Oct 08 '14 at 18:02
0

If by "built-in" you mean the function appendToEnd exists, then no.

However, its easy enough to do:

arr = arr.Select(s => s + " Test").ToArray();
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117