C# 常見的幾種集合的應用


寫代碼也很多年了,說一說c# 各種集合的比較與應用吧

1. ArrayList

ArrayList類似於數組,有人也稱它為數組列表。ArrayList可以動態維護,而數組的容量是固定的。它的索引會根據程序的擴展而重新進行分配和調整。和數組類似,它所存儲的數據稱為元素,它所保存的元素數就是它的容量。默認初始容量為0,在使用它時,需引入命名空間System.Connections;

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Demo
 7 {
 8     public class Student
 9     {
10         public Student() { }
11         public Student(string name, char sex, int age)
12         {
13             this.Name = name;
14             this.Sex = sex;
15             this.Age = age;
16         }
17         public string Name { get; set; }
18         public char Sex { get; set; }
19         public int Age { get; set; }
20     }
21 
22 }
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 using System.Diagnostics;
 7 
 8 namespace Demo
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             ArrayList array = new ArrayList();//實例化一個ArrayList集合對象
15             Student Zhang = new Student("張三", '', 22);
16             Student Li = new Student("李四", '', 20); 
17             Student Sun = new Student("小五", '', 21);
18 
19             Console.WriteLine("**********使用ArrayList 集合*********");
20             //用ArrayList的對象名添加Student對象
21             array.Add(Zhang);
22             array.Add(Li);       
23             array.Add(Sun);
24             Console.WriteLine("**********使用For循環遍歷**********");
25            
         for (int i = 0; i < array.Count; i++) 26 { 27 Student stu = (Student)array[i]; 28 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", stu.Name, stu.Age, stu.Sex); 29 } 30 31 Console.WriteLine("刪除Student張三的信息"); 32 array.Remove(Zhang);//用對象名刪除元素 33 Console.WriteLine("\n***********使用Foreach循環遍歷一***********"); 34 35 foreach (Student item in array) 36 { 37 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", item.Name, item.Age, item.Sex); 39 } 40 41 Console.WriteLine("\n***********使用Foreach循環遍歷二***********"); 42 foreach (Student item in array) 43 { 44 Student stu = (Student)item; 45 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", stu.Name, stu.Age, stu.Sex); 46 } 47 Console.WriteLine("\n***********使用Foreach循環遍歷三***********"); 48 foreach (var item in array) 49 { 50 Student stu = (Student)item; 51 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", stu.Name, stu.Age, stu.Sex); 52 } 53 } 54 } 55 }

2.HashTable

C# /提供了一種稱為HashTable的數據結構,通常稱為哈希表,有的人稱它為"字典".HashTable的數據是通過鍵(Key)和值(Value)來組織的,同ArrayList一樣,它也屬於System.Collections命名空間中,它所存放的每個元素都是鍵/值對.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 using System.Diagnostics;
 7 
 8 namespace Demo
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Hashtable hashtable = new Hashtable();//實例化一個HashTable集合對象

          Student Zhang = new Student("張三", '男', 22);
          Student Li = new Student("李四", '女', 20); 
          Student Sun = new Student("小五", '女', 21);

15             Console.WriteLine(" ***********使用HashTable集合***********");
16             hashtable.Add("張三", Zhang);
17             hashtable.Add("李四", Li);
18             hashtable.Add("小五", Sun);
19 Console.WriteLine("***********刪除Student李四的信息***********"); 20 hashtable.Remove("李四");//用鍵(key)移除元素

21 Console.WriteLine("\n***********使用Foreach循環遍歷集合的所有值一***********"); 22 foreach (Student item in hashtable.Values)//循環遍歷集合的值 23 { 24 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", item.Name, item.Age, item.Sex); 25 }
26 Console.WriteLine("\n***********使用Foreach循環遍歷集合的所有值二***********"); 27 foreach (Student item in hashtable.Values)//循環遍歷集合的值 28 { 29 Student stu = (Student)item; 30 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", stu.Name, stu.Age, stu.Sex); 31 }
32 Console.WriteLine("\n***********使用Foreach循環遍歷集合的所有值三***********"); 33 foreach (var item in hashtable.Values)//循環遍歷集合的值 34 { 35 Student stu = (Student)item; 36 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", stu.Name, stu.Age, stu.Sex); 37 } 38 39 Console.WriteLine("***********使用Foreach循環遍歷Name值******"); 40 foreach (string Name in hashtable.Keys)//循環遍歷集合的鍵(key) 41 { 42 Console.WriteLine("我的姓名是{0}", Name); 43 } 44 } 45 } 46 }

3. 泛型集合: List<T>

泛型是C#2.0中的一個新特性。泛型引入了一個新概念:類型參數。通過使用類型參數(T),減少了運行時強制轉換成裝箱操作的風險。通過泛型集合可以最大限度的重用代碼、保護類型的安全及提高性能。

不用點:List<T>對所保存元素做類型約束,而ArrayList可以增加任意類型。添加、讀取值類型元素 List<T>無需拆箱裝箱,而ArrayList需要做拆箱、裝箱處理。

相同點:通過索引訪問集合中的元素,添加、刪除元素方法相同

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 using System.Diagnostics;
 7 
 8 namespace Demo
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             List<Student> list = new List<Student>();//實例化一個List<>集合對象
15             
16             Student Zhang = new Student("張三", '', 22);
17             Student Li = new Student("李四", '', 20);  
18             Student Sun = new Student("小五", '', 21);
19 
20             Console.WriteLine("***********使用List<>集合***********");
21             list.Add(Zhang);
22             list.Add(Li);  
23             list.Add(Sun);
24 
25             Console.WriteLine("***********使用Foreach循環遍歷***********");
26             list.Remove(Sun);//移除集合元素Sun的信息
27             foreach (var item in list)
28             {
29                 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", item.Name, item.Age, item.Sex);
30             }
31   
32             list.RemoveAt(0);//移除集合中索引為0的元素
33             Console.WriteLine("***********使用For循環遍歷*********");
34             for (int i = 0; i < list.Count; i++)
35             {
36                 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", list[i].Name, list[i].Age, list[i].Sex);
37             }
38         }
39     }
40 }

4.泛型集合Dictionary<K,V>

它具有泛型的全部特性,編譯時檢查類型約束,獲取元素時無需類型轉換,並且它存儲數據的方式和HashTable類似。也是通過Key/Value對元素保存的。

不同點: Dictionary<K,V>對所保存的元素做類型約束,而HashTable可以增加任何類型。 Dictionary<K,V>添加、讀取值類型元素無需拆箱、裝箱,而HashTable需要做拆箱、裝箱處理

相同點:通過Key獲取Value, 添加、刪除、遍歷元素方法相同

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 using System.Diagnostics;
 7 
 8 namespace Demo
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Dictionary<string, Student> dictionary = new Dictionary<string, Student>();//實例化一個Directory<>集合對象
15             
16             Student Zhang = new Student("張三", '', 22);
17             Student Li = new Student("李四", '', 20);          
18             Student Sun = new Student("小五", '', 21);
19 
20             Console.WriteLine("*************使用Directory<>集合*************");
21             dictionary.Add("張三", Zhang);
22             dictionary.Add("李四", Li);  
23             dictionary.Add("小五", Sun);
24 
25             Console.WriteLine("*************使用Foreach循環遍歷***********");
26             foreach (var item in dictionary.Values)
27             {
28                 Console.WriteLine("我的姓名是{0},年齡是{1},性別是{2}", item.Name, item.Age, item.Sex);
29             }
30 
31             dictionary.Remove("李四");//移除集合中李四的信息
32 
33             Console.WriteLine("************使用Foreach循環遍歷Name值******");
34             foreach (string Name in dictionary.Keys)
35             {
36                 Console.WriteLine("我的姓名是{0}", Name);
37             }
39         }
40     }
41 }    
 1 using System;
 2 using System.Collections.Generic;
 3 public class Example
 4 {
 5          public static void Main()
 6          {
 7                //一、創建泛型哈希表,然后加入元素
 8                Dictionary<string, string> oscar = new Dictionary<string, string>();
 9                oscar.Add("哈莉?貝瑞", "《死囚之舞》");
10                oscar.Add("朱迪?丹奇", "《攜手人生》");
11                oscar.Add("尼科爾?基德曼", "《紅磨坊》");
12                oscar.Add("詹妮弗?康納利", "《美麗心靈》");
13                oscar.Add("蕾妮?齊維格", "《BJ單身日記》");
14 
15                //二、刪除元素
16                oscar.Remove("詹妮弗?康納利");
17 
18                //三、假如不存在元素則加入元素
19                if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不倫之戀》");
20                
21 
22                //四、顯然容量和元素個數
23                Console.WriteLine("元素個數: {0}", oscar.Count);
24 
25                //五、遍歷集合
26                Console.WriteLine("74屆奧斯卡最佳女主角及其電影:");
27                foreach (KeyValuePair<string, string> kvp in oscar)
28                {
29                       Console.WriteLine("姓名:{0},電影:{1}", kvp.Key, kvp.Value);
30                }
31 
32               //六、得到哈希表中鍵的集合
33               Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;
34               //遍歷鍵的集合
35               Console.WriteLine("最佳女主角:");
36               foreach (string s in keyColl)
37               {
38                    Console.WriteLine(s);
39               }
40 
41               //七、得到哈希表值的集合
42               Dictionary<string, string>.ValueCollection valueColl = oscar.Values;
43               //遍歷值的集合
44               Console.WriteLine("最佳女主角電影:");
45               foreach (string s in valueColl)
46               {
47                    Console.WriteLine(s);
48               }
49 
50               //八、使用TryGetValue方法獲取指定鍵對應的值
51               string slove = string.Empty;
52               if (oscar.TryGetValue("朱迪?丹奇", out slove))
53                      Console.WriteLine("我最喜歡朱迪?丹奇的電影{0}", slove);
54               else
55                      Console.WriteLine("沒找到朱迪?丹奇的電影");
56 
57               //九、清空哈希表
58               oscar.Clear();
59               Console.ReadLine();
60        }
61 }

5. 數組

1. 定義

首先,給定類型的數組只能保存該類型的元素。其次要規定數組的維數,可以用幾何的知識理解數組的維數,可以用一維坐標軸來理解一維數組;用平面直角坐標系來理解二維數組;用三維立體坐標系來理解三維數組等。再次,數組必須規定每個維數的大小。

int[] anIntArray;    //定義數組

anIntArray={1,2,3};//上述代碼定義了一個數組並對其進行了初始化。可以一次完成

int [] sz=newint[];   //初始化數組,如果不指定大小,報語法錯誤。

anIntArray=new  int[]{1,2,3};//用new關鍵字初始化數組的元素

anIntArray=new  int[3]{1,2,3};//指定數組大小用new關鍵字初始化數組元素

數組還有另外一種初始化方式,即指定數組大小並用new關鍵字初始化數組的元素:

int[] anIntArray=new  int[3];

執行時.NET將會為數組中的每一個元素賦予同一個(定義類型的)默認值。對於Int型的變量來說這個默認值是0。

2、數組的索引

數組的索引也就是通常所說的數組下標,英文為Index。數組的索引是從0開始的。

3、數組的遍歷

C#提供了foreach語句以實現數組的遍歷功能。可以使用foreach語句訪問數組中的每個元素而不需要確切地知道每個元素的索引。

int[] myArray=new int[5]  {14, 25, 7,36, 53};

//采用foreach語句對myArray進行遍歷

foreach(int number inmyArray)

Console.Write(number);

for (int i= 0; i < 5; i++)

Console.Write(myArray[i]);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM