标签:
集合,表示可以通过遍历每个元素来访问的一组对象(特别是可使用foreach循环访问),一个集合包括多个元素,即有一个集合类对象和N个元素对象。
集合不同于数组,是一组可变类型的、可变数量的元素的组合,这些元素可能共享某些特征,需要以某种操作方式一起进行操作。一般来讲,为了便于操作这些元素的类型是相同的。
在使用集合以前,我们要在程序的开头引入using System.Collections空间。 而在C#中Collections为我们提供的集合有ArrayList、Stack、Queue、Hashtable等。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Collections; 5 6 namespace ConsoleApplication1 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 /*---------------- 13 * 动态数组 | 14 * --------------- 15 * 16 ArrayList al = new ArrayList(); 17 al.Add("a"); 18 al.Add(65); 19 int count = al.Count; 20 al.Capacity = 5; //设置容量 21 al.RemoveAt(0); 22 al.Insert(0, 66); 23 Console.WriteLine(al[0]); 24 al.Clear();*/ 25 26 /*------------ 27 * 栈-后进先出| 28 * ----------- 29 * 30 Stack s = new Stack(); 31 s.Push(1); 32 s.Push(10); 33 int count = s.Count;//2 34 Console.WriteLine(s.Pop());//10 35 Console.WriteLine(s.Pop());//1*/ 36 37 /*-------------- 38 * 队列-先进先出| 39 * ------------- 40 * 41 Queue q = new Queue(); 42 q.Enqueue(‘A‘); // 增加元素 43 q.Enqueue(‘M‘); 44 q.Enqueue(‘G‘); 45 q.Enqueue(‘W‘); 46 47 Console.WriteLine("Current queue: "); // A M G W 48 foreach (char c in q) 49 Console.Write(c + " "); 50 Console.WriteLine(); 51 q.Enqueue(‘V‘); 52 q.Enqueue(‘H‘); 53 Console.WriteLine("Current queue: "); // A M G W V H 54 foreach (char c in q) 55 Console.Write(c + " "); 56 Console.WriteLine(); 57 Console.WriteLine("Removing some values "); 58 char ch = (char)q.Dequeue(); //移除元素 59 Console.WriteLine("The removed value: {0}", ch); // A 60 ch = (char)q.Dequeue(); 61 Console.WriteLine("The removed value: {0}", ch); // M */ 62 63 64 /*------------------- 65 * 哈希表-键与值对应| 66 * ----------------- 67 Hashtable ht = new Hashtable(); //声明ht 68 //key值唯一,value值可以重复. 69 ht.Add("E", "e");//添加key/键值对 70 ht.Add("A", "a"); 71 ht.Add("C", "c"); 72 ht.Add("B", "b"); 73 foreach (string sv in ht.Values) 74 { 75 Console.WriteLine(sv); 76 } 77 foreach (string sv in ht.Keys) 78 { 79 Console.WriteLine(sv); 80 } 81 82 string s = (string)ht["A"]; 83 if (ht.ContainsKey("E")) //判断哈希表是否包含特定键,其返回值为true或false 84 Console.WriteLine("the E key:exist"); 85 ht.Remove("C");//移除一个key/键值对 86 Console.WriteLine(ht["A"]);//此处输出a 87 ht.Clear();//移除所有元素 88 Console.WriteLine(ht["A"]); //此处将不会有任何输出*/ 89 /* 90 * Hashtable常用的属性有Count、Keys、Values, 91 * 其中:Count是获取Hashtable中的元素个数, 92 * Keys表示获取 Hashtable 中的键的集合, 93 * Values 表示 Hashtable 中的所有值的集合。 94 */ 95 96 97 98 99 Console.ReadKey(); 100 } 101 } 102 }
标签:
原文地址:http://www.cnblogs.com/jin521/p/5735394.html