将新项添加到字符串数组

时间:2016-11-01 19:04:31

标签: c# arrays

我正在尝试将2个新数组项添加到现有字符串数组中。我取得了成果,但我确信这不是正确的做法。

如何将项添加到字符串数组中。

string[] sg = {"x", "y" };    
string[] newSg = {"z", "w"};

string[] updatedSg = new string[sg.Length+newSg.Length];
for (int i = 0; i < sg.Length; i++)
{
    updatedSg[i] = sg[i];
}
for (int i = 0; i < newSg.Length; i++)
{
    updatedSg[sg.Length+i] = newSg[i];
}

4 个答案:

答案 0 :(得分:5)

无法向数组中添加项目。您可以使用其他容器类型(如List),也可以使用更多元素创建 new 数组,并复制旧元素。但是您无法向数组添加元素,也无法从数组中删除元素。数组中的元素数量是固定的。

答案 1 :(得分:4)

您可以使用 Linq Concat两个数组合并为一个:

 string[] updatedSg = sg
   .Concat(newSg)
   .ToArray();

另一种方法是使用List<String>代替updatedSg集合类型而不是数组:

 List<string> updatedSg = new List<string>(sg);

 updatedSg.AddRange(newSg);

如果您坚持更新 现有数组,那么在一般情况中,您可以拥有:

 // imagine we don't know the actual size 
 string[] updatedSg = new string[0];

 // add sg.Length items to the array
 Array.Resize(ref updatedSg, sg.Length + updatedSg.Length);

 // copy the items
 for (int i = 0; i < sg.Length; ++i)
   updatedSg[updatedSg.Length - sg.Length + i - 1] = sg[i]; 

 // add updatedSg.Length items to the array
 Array.Resize(ref updatedSg, newSg.Length + updatedSg.Length);

 // copy the items 
 for (int i = 0; i < newSg.Length; ++i)
   updatedSg[updatedSg.Length - newSg.Length + i - 1] = newSg[i]; 

答案 2 :(得分:0)

使用CopyTo()

var updatedSg  = new string[sg.Length + newSg.Length];
sg.CopyTo(updatedSg, 0); 
sgNew.CopyTo(updatedSg, sg.Length);

在这里回答 https://stackoverflow.com/a/1547276/7070657

或根据某人的建议:

var temp = x.Length;
Array.Resize(ref x, x.Length + y.Length); 
y.CopyTo(x, temp); // x and y instead of sg and sgNew

答案 3 :(得分:0)

如果我必须动态地向数组添加项目,我会使用List而不是Array(Lists有一个非常有用的Add()方法)。您甚至可以在流程结束时将其转换为数组(使用ToArray()方法)。但您也可以使用如上所述的Concat()等方法。