前言
本節主要是來了解學習集合,以方便在程序編寫時,什么地方該選用什么集合,讓程序更健壯的運行起來。在學習了解集合之前,首先需要了解一些數據結構方面的知識。下面我們就先簡單的來看一下數據結構。
數據結構
數據結構就是相互之間存在一種或多種特定關系的數據元素的集合。 程序界有一點很經典的話,程序設計=數據結構+算法。用源代碼來體現,數據結構,就是編程。
集合分類
在上圖中可以看到,集合總體上分為線性集合和非線性集合。線性集合按照存儲方式又分為直接存儲和順序存儲。
直接存儲,是指該類型的集合數據元素可以直接通過下標(即index)來訪問,在C#中直接存儲的數據結構有三類:Array(包含數組和List<T>)、string、struct。
直接存儲結構的優點是:向數據結構中添加元素是很高效的,直接放在數據末尾的第一個空位上就可以了。
直接存儲結構的缺點是:向集合插入元素將會變得低效,它需要給插入的元素騰出位置並順序移動后面的元素。
順序存儲結構,即線性表。線性表可動態的擴大和縮小,它在一片連續的區域中存儲數據元素。線性表不能按照索引進行查找,它是通過對地址的引用來搜索元素的,為了找到某個元素,它必須遍歷所有元素,直到找到對應的元素為止。所以,線性表的優點是插入和刪除數據效率高,缺點是查找的效率相對來說低一點。
線性表有可以分為隊列、棧以及索引群集,在C#中分別表現為:Queue<T>、Stack<T>,索引群集又進一步泛化為字典類型Dictionary<TKey,TValue>和雙向鏈表LinkedList<T>。
非線性集合自己在實際應用中比較少,而且感覺也比較復雜,所以在此先不做討論學習。下面我們就來一一的學習一下日常使用比較頻繁的集合吧。
數組
數組就是包含同一類型的多個元素。
數組的聲明:int[] intArray;
注意:數組聲明時,方括號([])必須跟在類型的后面,而不是變量名的后面。在C#中,將方括號放在變量名后是不合法的語法。
數組的初始化:
我們知道數組是引用類型,所以需要給他們分配堆上的內存。
1、intArray=new int[3];
2、intArray=new int[]{1,2,3};
3、int[] intArray={1,2,3};
數組在聲明和初始化后,可以使用索引器進行訪問,索引器總是以0開頭,表示第一個元素。
多維數組:
一般可以是一維數組,二維數組、三維數組、多維數組。下面簡單的來看一下數組吧
///最簡單的一維數組 int[] intArray = { 1, 2, 3 }; ///二維數組,兩行三列(類似X軸和Y軸平面幾何) int[,] intTwoArray=new int[2,3]; intTwoArray[0, 0] = 0; intTwoArray[0, 1] = 1; intTwoArray[0, 2] = 2; intTwoArray[1, 0] = 3; intTwoArray[1, 1] = 4; intTwoArray[1, 2] = 5; ///二維數組,三行四列 int[,] intTwoArray2 = new int[,] { { 1, 11, 111 }, { 2, 22, 222 }, { 3, 33, 333 }, { 4, 44, 444 } }; ///三維數組,三行三列 int[, ,] intThreeArray; intThreeArray = new int[,,] { { {1,1}, {11,11}, {111,111} }, { {2,2}, {22,22}, {222,222} }, { {3,3}, {33,33}, {333,333} }, { {4,4}, {44,44}, {444,444} } };
上面簡單的介紹說明了一下一維數組、二維數組和三維數組。
ArrayList
ArrayList類繼承了以下幾個接口
public class ArrayList : IList, ICollection, IEnumerable, ICloneable
以下來看一下ArrayList的基本操作
///定義一個一維數組 int[] intArray = { 1, 2, 3 }; ///直接將一維數組轉換為ArrayList; ArrayList array = new ArrayList(intArray); ///Add方法 array.Add(5); ///Insert方法兩個參數,索引位置和值 array.Insert(3, 7); ////刪除元素 ///直接刪除Array中的指定元素 array.Remove(3); ////刪除索引位置為3的元素 array.RemoveAt(3); ////刪除一個范圍,從Array中索引為1的元素開始刪除三個元素 array.RemoveRange(1, 3); ///Array的遍歷 foreach (int i in intArray) { Console.WriteLine(i); } ///查找元素 ///查找元素為5,返回值為索引 array.IndexOf(5); ////查找元素為5的,返回值為true/false array.Contains(5); Console.ReadLine();
List<T>
List<T>類是 ArrayList 類的泛型等效類。 該類使用大小可按需動態增加的數組實現 IList<T> 泛型接口。
看看List<T>所繼承的接口
// 摘要: // 表示可通過索引訪問的對象的強類型列表。提供用於對列表進行搜索、排序和操作的方法。 // // 類型參數: // T: // 列表中元素的類型。 [Serializable] [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
T就是列表中元素的類型,下面我們以string為例進行說明一下List<T>的基本用法。在測試過程中發現List<T>與ArrayList的操作基本完全類似。主要也是它們共同繼承了IList,ICollection,IEnumerable三個接口。
T當然也可以是自定義的類型,這也是我們在日常的編程中應用最為廣泛的。首先來定義一個實體
public class Person { public string FirstName { get; set; } public string LastName { get; set; } }
接下來進行定義和初始化操作
List<Person> list = new List<Person>(); list.Add(new Person() { FirstName="aehyok",LastName="Kris"}); list.Add(new Person() { FirstName = "aehyok", LastName = "Leo" });
因為操作和上面的ArrayList基本是完全一樣的,所以在此就不做過多的介紹了。
Dictionary
1、Dictionary的普通用法
Dictionary<string, string>是一個泛型。它本身有集合的功能有時候可以把它看成數組。它的結構是這樣的:Dictionary<[key], [value]>,它的特點是存入對象是需要與[key]值一一對應的存入該泛型,通過某一個一定的[key]去找到對應的值。
static void Main(string[] args) { ///聲明一個Dictionary對象 Dictionary<string, string> dictionaryList = new Dictionary<string, string>(); ///向集合中添加元素 dictionaryList.Add("1", "aehyok"); dictionaryList.Add("2", "Kris"); dictionaryList.Add("3", "Leo"); ////通常添加元素的時候都會先判斷此鍵是否已經存在的 if (dictionaryList.ContainsKey("4")) { dictionaryList.Add("4","Niki"); } ////訪問元素 string str=dictionaryList["4"]; ///遍歷key foreach (var key in dictionaryList.Keys) { Console.WriteLine("OutPut Key:{0}", key.ToString()); } ////遍歷value foreach (string value in dictionaryList.Values) { Console.WriteLine("OutPut Value:{0}", value); } ///循環遍歷key和value foreach (var dic in dictionaryList) { Console.WriteLine("OutPut Key:{0},Value:{1}",dic.Key,dic.Value); } //移除鍵值是4的元素 dictionaryList.Remove("4"); }
2、將dictionary<key,value> 的value當成一個數組
Dictionary<string,string[]> stringList=new Dictionary<string,string[]>(); stringList.Add("1",new string[]{"北京","深圳","上海","廣州"}); stringList.Add("2",new string[]{"重慶","武漢","南京"}); Console.WriteLine("OutPut:" + stringList["1"][1]);
3、將Dictionary<key,value> 的value當成一個實體類
public class Person { public string FirstName { get; set; } public string LastName { get; set; } } static void Main(string[] args) { Dictionary<string,Person> personList=new Dictionary<string,Person>(); Person person = null; for (int i = 0; i < 3; i++) { person = new Person(); person.FirstName = "aehyok"; person.LastName = "Kris"; personList.Add(i.ToString(),person); } foreach (var student in personList) { Console.WriteLine("Output : Key {0}, FirstName : {1}, LastName {2}", student.Key, student.Value.FirstName, student.Value.LastName); } }
4、文章篇幅有限,關於dictionary有關擴展方法暫時不在此進行介紹,如有興趣可以參見大神作品http://www.cnblogs.com/ldp615/archive/2011/01/28/dictionary-extensions.html
總結
其實可以發現它們大體的基本操作是類似的,也就是他們擁有繼承共同的接口。這里也只是簡單的介紹了我覺得最常見的幾個集合的使用。