C#进阶之路——5. C#数组与集合
基础:
C#的数据组合分为数组和集合两种。 |
|
数组 |
一维数组和多维数组 |
集合 |
普通集合:泛型集合,哈希表,字典表,特殊集合等; |
特殊集合:队列和堆栈等 |
数组 |
|
一维数组 |
|
int[] 数组名 = new int[2]{1,2} |
方括号里是数组的长度 |
多维数组 |
|
int[] 数组2 = new int[2,3]{ {2,3,4} {5,6,7} } |
方括号里数字表示2维数组 每个维度的数组长度是3 |
集合 |
|
注意:集合需要在代码开头加 using System.Collections; |
|
普通集合 |
|
ArrayList |
不限制类型 不限定长度 不能更改索引值 只能是0123 |
List |
限制数据类型 不限制长度 不能更改索引值 |
HashTable |
没有顺序的概念 不限制类型 不限制长度 不限制索引值 |
Dictionary |
限制类型 限制索引值 不限制长度 |
注意:ArrayList集合对数据类型没有要求,因为ArrayList集合中存储的数据类型默为object类型,其它类型与object类型进行转换时发生“拆箱装箱”操作,
而List集合在声明集合时确定了数据类型,所以List集合与ArrayList集合相比相对安全。
进阶:
ArrayList |
添加数据时不需要规定类型 |
ArrayList 集合1=new ArrayLisr(); 集合1.Add("abc"); 添加字符串 集合1.Add(123); 添加数字 集合1.Add(true); 添加布尔型数据 |
|
集合1.Remove(123) 移除数据 集合1.Clear() 清空集合 集合1.Contains("123") 检查集合是否包含该数据 集合1.Insert(0,123) 在索引值为0的位置插入123数据 |
ArrayList示例 |
static void Main(string[] args) { ArrayList list = new ArrayList(); list.Add(true); list.Add(1); list.Add("张三"); list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }); list.AddRange(list); //list.Clear();//清除 //list.Reverse();//反转 //list.InsertRange(0, new string[] {"李四"});//指定位置插入集合 if (list.Contains("张三"))//判断包含指定元素 { Console.WriteLine("已经有这个小哥哥啦~"); } for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); } Console.ReadKey(); } |
泛型集合 |
||
List |
限制数据类型 不限制长度 不能更改索引值 |
|
List<数据类型> 集合2 = new List <数据类型>(); |
新建泛型集合 |
|
集合2.Add("数据") |
添加数据时需要规定类型 |
|
List示例 |
static void Main(string[] args) { List<int> lt = new List<int>(); lt.Add(1); lt.Add(2); lt.Add(3); lt.AddRange(new int[] { 4, 5, 6, 7, 8, 9 }); for (int i = 0; i < lt.Count; i++) { Console.WriteLine(lt[i]); } Console.ReadKey(); } |
哈希表 |
||
hashtable |
没有顺序的概念 不限制类型 不限制长度 不限制索引值 |
|
Hashtale 集合3 = new Hashtable(); 集合3.Add(索引值,数据) 集合3.Values集合的数据值 //配合遍历使用输出数据,否则输出对象类型 集合3.Keys 集合的索引值 |
添加数据时需要指定索引值 索引值和数据可以是任意数据类型 |
|
Hashtable示例 |
static void Main(string[] args) { Hashtable hash = new Hashtable(); hash.Add(1, "张三"); hash.Add(2, true); hash.Add(false, "错误的~"); foreach (var h in hash.Keys) { Console.WriteLine("键是{0},值是{1}", h, hash[h]); } Console.ReadKey(); } |
字典表 |
||
Dictionary |
限制类型限制索引值 不限制长度 |
|
Dictionary<索引值数据类型,数据类型> 集合4 = new Dictionary<索引值数据类型,数据类型>();集合4.Add(索引值,数据) |
添加的索引值和数据必须符合建表时规定的类型 |
|
static void Main(string[] args) { Dictionary<int, string> dir = new Dictionary<int, string>(); dir.Add(1, "张三"); dir.Add(2, "李四"); dir[1] = "干掉你"; foreach (KeyValuePair<int, string> kv in dir) { Console.WriteLine("键是{0},值是{1}", kv.Key, kv.Value); } Console.ReadKey(); } |
队列 |
||
Queue |
先进先出 |
|
Queue 队列 = new Queue(); 新建队列 队列.Enqueue("数据") 添加数据 队列.Dequeue() 移除最先添加的数据 |
||
堆栈 |
||
Stack |
先进后出 |
|
Stack 堆栈 = new Stack(); 新建堆栈 堆栈.Push("数据") 添加数据 堆栈.Pop(); 移除最后添加的数据 |
||
循环遍历数组 |
|
for (int i=0;i<数组1.Count;i++) { Console.Write( 数组1[i].ToString() + 数组1[i].GetType().ToString(); ) } |
数组1.Count 数组长度 GetType()获取数据类型 //这种循环方式只能用于索引值为数字的类型 |
foreach(var x in 数组1) { Console.Write( 数组1[i].ToString() + 数组1[i].GetType().ToString(); ) } |
//这个循环可以遍历任何类型的数组 |
参考: