向C#数组添加元素 [英] Adding elements to a C# array
问题描述
我想以编程方式在C#中向字符串数组添加或删除一些元素,但仍保留以前的内容,有点像VB函数
I would like to programmatically add or remove some elements to a string array in C#, but still keeping the items I had before, a bit like the VB function ReDim Preserve.
推荐答案
显而易见的建议是改用 List< string>
,您将从其他答案中已经读过.这绝对是实际开发场景中的最佳方法.
The obvious suggestion would be to use a List<string>
instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.
当然,我想让事情变得更有趣(就是我今天),所以我将直接回答您的问题.
Of course, I want to make things more interesting (my day that is), so I will answer your question directly.
以下是几个函数,这些函数将从 string []
...
Here are a couple of functions that will Add and Remove elements from a 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;
}
这篇关于向C#数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!