阅读量:2
在C#中,有多种类型的集合可以用来存储和管理数据。以下是一些常见集合类型以及如何向它们添加新元素的示例:
- List
using System.Collections.Generic;
List<int> myList = new List<int>(); // 创建一个整数列表
myList.Add(1); // 添加新元素1
myList.Add(2); // 添加新元素2
- ArrayList
using System.Collections;
ArrayList<int> myArrayList = new ArrayList<int>(); // 创建一个整数数组列表
myArrayList.Add(1); // 添加新元素1
myArrayList.Add(2); // 添加新元素2
- Dictionary
using System.Collections.Generic;
Dictionary<string, int> myDictionary = new Dictionary<string, int>(); // 创建一个字符串到整数的字典
myDictionary.Add("one", 1); // 添加新元素:键为"one",值为1
myDictionary.Add("two", 2); // 添加新元素:键为"two",值为2
- HashSet
using System.Collections.Generic;
HashSet<int> myHashSet = new HashSet<int>(); // 创建一个整数集合
myHashSet.Add(1); // 添加新元素1
myHashSet.Add(2); // 添加新元素2
请注意,在使用集合时,可能需要根据实际情况选择合适的集合类型。例如,如果需要存储唯一的元素,可以使用HashSet
以上就是关于“c#集合怎样添加新元素”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm