将元素添加到C#数组

我想以编程方式在C#中向字符串数组添加或删除一些元素,但仍然保留我以前的项目,有点像VB函数ReDim Preserve 。

显而易见的建议是使用List ,您将从其他答案中读取。 这绝对是真实开发场景中的最佳方式。

当然,我想让事情变得更有趣(我的那一天),所以我会直接回答你的问题。

这里有一些函数可以添加和删除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; } 

如果你真的不会(或不能)使用generics集合而不是你的数组, 那么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 

由于数组实现IEnumerable您可以使用Concat

 string[] strArr = { "foo", "bar" }; strArr = strArr.Concat(new string[] { "something", "new" }); 

或者更合适的是使用支持内联操作的集合类型。

不要使用数组 – 使用通用List ,它允许您动态添加项目。

如果这不是一个选项,则可以使用Array.CopyArray.CopyTo将数组复制到更大的数组中。

使用List而不是string[]

List允许您添加和删除性能良好的项目。

您应该看一下List 对象 。 列表往往更好地动态改变你想要的。 arrays不是那么多……

您可以使用通用集合,例如List <>

 List list = new List(); // add list.Add("element"); // remove list.Remove("element"); 

什么是这个:

List tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

您可以使用此代码段:

 static void Main(string[] args) { Console.WriteLine("Enter number:"); int fnum = 0; bool chek = Int32.TryParse(Console.ReadLine(),out fnum); Console.WriteLine("Enter number:"); int snum = 0; chek = Int32.TryParse(Console.ReadLine(),out snum); Console.WriteLine("Enter number:"); int thnum = 0; chek = Int32.TryParse(Console.ReadLine(),out thnum); int[] arr = AddToArr(fnum,snum,thnum); IOrderedEnumerable oarr = arr.OrderBy(delegate(int s) { return s; }); Console.WriteLine("Here your result:"); oarr.ToList().FindAll(delegate(int num) { Console.WriteLine(num); return num > 0; }); } public static int[] AddToArr(params int[] arr) { return arr; } 

我希望这对你有所帮助,只需更改类型即可