C#-集合
阿新 • • 發佈:2022-02-19
概念
陣列是一組用來儲存型別一樣的連串資料,如果元素個數是動態的,陣列就無法滿足使用要求。這個時候就會用到集合。所以集合就是用來儲存長度不固定的一連串資料,並且具有一定的邏輯性和資料儲存結構。集合是同一型別元素(物件)的組合,本身也是一個類(物件),就像一個容器一樣,(可以)裝著它的元素。
常見的集合
佇列、棧、連結串列、字典和集。List<T>就是一種泛型集合,且它與陣列功能相當,長度可變。
集合介面的和型別
絕大多數的集合在System.Collections和System.Collections.Generic名稱空間中都能夠找到。一些特殊的集合則需要在System.Collections.Specialized名稱空間內。執行緒安全的集合類位於System.Collections.Concurrent名稱空間內。
一般而言,集合大多都繼承了一些介面以便實現共有的方法。常見的介面如下:
IEnumerable<T>
此介面通常可用來實現輪詢功能。例如將foreach語句實現在集合上,就需要繼承此介面。這個介面定義了方法GetEnumerator(),它返回實現IEnumratator介面的列舉。
其他介面還有ICollection<T>,IList<T>,ISet<T>,IDictionary<Tkey,Tvalue>,ILookup<Tkey,Tvalue>,IComparer<T>,IEqualityComparer<T>,IProducerConsumerCollection<T>等等......
List<T>初窺
//所有泛型集合都在該名稱空間下 using System.Collections.Generic;
初始化方法
List<string> student = new List<string>(); List<string> student = new List<string> { "wf", "xr", "jym" };
對比陣列和集合:
int[] ages = new int[] { 16, 23, 25, 22 }; List<int> ages = new List<int> { 16, 23, 25, 23, 22 };
增刪改查:
student.Add("xm"); student.Insert(3, "xm"); student.Remove("xr"); student.RemoveAt(0); student.clear(); student[0] = "dfg"; Console.WriteLine(student.BinarySearch("dfg")); Console.WriteLine(student.IndexOf("jym")); Console.WriteLine(student.Contains("jym"));
文章轉載自:軟體開發平臺
地址:https://www.hocode.com/