[英]What's the best way to add an item to a C# array?
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: 我没有找到连接2个数组的扩展方法,我想做类似的事情:
numbers = numbers.Concat(new[] { valueToAdd });
To concatenate 2 ararys look at: How do I concatenate two arrays in C#? 要连接2 ararys看看: 如何在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). 并在需要时调用ToArray()扩展方法(而不是相反)。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.