C#在具有现有大小的数组中添加和删除元素 [英] C# Adding and Removing elements to an array with an existing size

查看:62
本文介绍了C#在具有现有大小的数组中添加和删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是有一个问题.我注意到,与C ++不同,C#在处理数组时有点复杂.我一直在数组中寻找的功能或技术之一是:我想以一种更高效,更简单的方式添加元素或从中删除元素.

I just have a question. I noticed that unlike C++, C# is a bit complicated when it comes to array. One of the features or techniques I've been looking for in the array is that: I want to add elements or remove elements from it in a more efficient and simpler way.

例如,我有一个名为"food"的数组.

Say for example, I have an array called 'food'.

string[] food = {'Bacon', 'Cheese', 'Patty', 'Crabs'}

然后我决定添加更多的食物.如我所见,C#存在问题,除非您确实使用ArrayList,否则这是不可能做的.数组本身呢?我想将数组用作添加物品的某种清单.

Then I decided to add more food. Problem with C# as I can see it is this isn't possible to do unless you do use an ArrayList. How about for an array itself? I want to use the array as some sort of inventory where I add things.

非常感谢!

推荐答案

如果不分配新数组,就无法使用C#中的数组来做到这一点.因为数组的大小是固定的.

You can't do that with arrays in C# without allocating a new array. Because arrays are fixed in size.

如果您希望能够从容器中添加/删除元素,则可以使用 List< T> .或者,您可以使用 ArrayList ,但不建议这样做,因为在大多数情况下, List< T> 具有性能优势.

If you want to be able to add/remove elements from a container, you could use List<T>. Alternativly you could use an ArrayList but that is not recommended, since in most cases List<T> has a performance advantage.

内部都使用数组作为数据的默认容器.他们还负责根据您放入集合或取出的数据量来调整容器的大小.

Internally both use an array as the default container for your data. They also take care of resizing the container according to how much data you put in the collection or take out.

在您的示例中,您将使用类似

In your example, you would use a list like

 List<string> food = new List<string> { "Bacon", "Cheese", "Patty", "Crabs" };

 food.Add("Milk"); //Will add Milk to the list
 food.Remove("Bacon"); //Will remove "Bacon"

在MSDN上的列表:文档

List on MSDN: Docs

这篇关于C#在具有现有大小的数组中添加和删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆