3

I have the following array:

int[] numbers;

Is there a good way to add a number to the array? I didn't find an extension method that concats 2 arrays, I wanted to do something like:

numbers = numbers.Concat(new[] { valueToAdd });
NofBar
  • 116
  • 6
  • 3
    You concatenation is almost correct , it just needs a `.ToArray()` at the end. But if you're going to do it many times, it is better to use a `List` or other appropriate collection. – Allon Guralnek May 18 '13 at 21:28

2 Answers2

9

To concatenate 2 ararys look at: How do I concatenate two arrays in C#?

The best solution I can suggest is to simply use

List<int> numbers

And when needed call the ToArray() extension method (and not the opposite).

Community
  • 1
  • 1
Adam Tal
  • 5,911
  • 4
  • 29
  • 49
0

you can try this..

var z = new int[x.length + y.length];
x.CopyTo(z, 0);
y.CopyTo(z, x.length);

or

List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();

or

int[] array1 = { 1, 3, 5 };
int[] array2 = { 0, 2, 4 };

// Concat array1 and array2.
var result1 = array1.Concat(array2);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
sanjeev
  • 590
  • 1
  • 11
  • 21