我想以编程方式向C#中的字符串数组添加或删除一些元素,但仍然保留以前拥有的项,有点像VB函数ReDim Preserve。
发布于 2012-03-06 01:27:25
最明显的建议是使用List<string>,您可能已经从其他答案中读到过。在实际的开发场景中,这绝对是最好的方式。
当然,我想让事情更有趣(这是我的一天),所以我会直接回答你的问题。
下面是几个在string[]中添加和删除元素的函数……
string[] Add(string[] array, string newValue){
int newLength = array.Length + 1;
string[] result = new string[newLength];
for(int i = 0; i < array.Length; i++)
result[i] = array[i];
result[newLength -1] = newValue;
return result;
}
string[] RemoveAt(string[] array, int index){
int newLength = array.Length - 1;
if(newLength < 1)
{
return array;//probably want to do some better logic for removing the last element
}
//this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way
string[] result = new string[newLength];
int newCounter = 0;
for(int i = 0; i < array.Length; i++)
{
if(i == index)//it is assumed at this point i will match index once only
{
continue;
}
result[newCounter] = array[i];
newCounter++;
}
return result;
}发布于 2012-03-06 01:28:18
如果你真的不想(或者不能)使用泛型集合而不是数组,Array.Resize就是C#版本的redim preserve:
var oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0发布于 2012-03-06 01:17:16
不要使用数组-使用一个通用的List,它允许你动态添加项目。
如果不能这样做,可以使用Array.Copy或Array.CopyTo将数组复制到更大的数组中。
https://stackoverflow.com/questions/9570944
复制相似问题