如何在不覆盖的情况下将数据从一个数组复制到另一个数组

How copy the data from a array to another array without overwrite

如何在 MVC C# 中将数据从一个数组复制到另一个数组而不覆盖它。

string[] total = new {"Apple", "Banana", "Cat"};
string[] arrayA= new {"Donkey", "Ear", "Frog"};
total= new List<string>().Concat(arrayA).ToArray();

这段代码基本上只是从arrayA复制数据并覆盖它。那么有没有办法从 arrayA 添加或复制数据并将其添加到 totalstring[] total = new List<string>().Concat(arrayA).ToArray(); 之后,我的 total 值变为 arrayA 并且 total 中的值被覆盖。

  1. 数组复制到

在复制数据方面,您可以使用 CopyTo 解决方案,如上:

var source = new string[] { "1", "2", "3" };
var target = new string[3];

try
{
  source.CopyTo(target, 0);
}
catch (InvalidCastException)
{
  foreach (var element in target)
  {
    Console.WriteLine(element);
  }
}
  1. 将数组转换为列表

如果你想追加一个数组,你不能以正确的方式做到这一点(没有设置目标数组的最大值 number/length 和浪费内存)。列表是更好的选择(数组的转换到列表可能是你正在搜索的内容)。

List<int> lst = ints.OfType<string>().ToList();
  1. 阵列克隆

另一种选择是克隆整个数组,这意味着对数组项执行浅拷贝。

var source = new[] { "aa", "bb", "cc" };
var target = (string[])source.Clone();

您应该制作 total 列表,因为您想要用新条目扩展它:

List<string> total = new List<string> { "Apple", "Banana", "Cat" };

然后您可以使用 AddRange 添加来自 arrayA:

的所有值
total.AddRange(arrayA);

如果你真的需要一个数组那么这应该可以,尽管 List 选项仍然更好:

string[] total = new {"Apple", "Banana", "Cat"};
string[] arrayA = new {"Donkey", "Ear", "Frog"};
total = total.Concat(arrayA).ToArray();

还有一个 'Array.Resize' method. Ultimately this just creates a new array and copies the data 所以它并不比上面的 LINQ 方法好多少:

string[] total = new {"Apple", "Banana", "Cat"};
string[] arrayA = new {"Donkey", "Ear", "Frog"};
int initialTotalLength = total.Length;
// resize the array
Array.Resize(ref total, total.Length + arrayA.Length);
// append the new entries to the "empty" positions in the array
arrayA.CopyTo(total, initialTotalLength);

您必须创建另一个变量并在其中存储组合数组 var arrayA = [1, 2]; var arrayB = [3, 4];

var newArray = arrayA.concat(arrayB);

newArray 的值将是 [1, 2, 3, 4](arrayA 和 arrayB 保持不变;concat 创建并 returns 结果的新数组)。

使用参考