C# 容器 C# 集合

int[] arr = {1,2,3,4,5};
int currIndex; //當前下標
int indexLeft = 0; //第一個下標,最左邊的下標
int indexRight = arr.Length - 1; //最後一個下標,最右邊的下標

//正序遍歷
Console.WriteLine("數組arr總共有" + arr.Length + "個元素。");
Console.WriteLine("數組arr正序遍歷");

for (currIndex = indexLeft; currIndex <= indexRight; currIndex++)
{
    int item = arr[currIndex];//當前元素
    Console.WriteLine("arr[" + currIndex + "] = " + item + ",數組arr當前下標:" + currIndex + ",值: " + item);
}

//倒序遍歷
Console.WriteLine("數組arr倒序遍歷");
for (currIndex = indexRight; currIndex >= indexLeft; currIndex--)
{
    int item = arr[currIndex];//當前元素
    Console.WriteLine("arr[" + currIndex + "] = " + item + ",數組arr當前下標:" + currIndex + ",值: " + item);
}

output:

數組arr總共有5個元素。
數組arr正序遍歷
arr[0] = 1,數組arr當前下標:0,值: 1
arr[1] = 2,數組arr當前下標:1,值: 2
arr[2] = 3,數組arr當前下標:2,值: 3
arr[3] = 4,數組arr當前下標:3,值: 4
arr[4] = 5,數組arr當前下標:4,值: 5
數組arr倒序遍歷
arr[4] = 5,數組arr當前下標:4,值: 5
arr[3] = 4,數組arr當前下標:3,值: 4
arr[2] = 3,數組arr當前下標:2,值: 3
arr[1] = 2,數組arr當前下標:1,值: 2
arr[0] = 1,數組arr當前下標:0,值: 1

下標邊界檢查

//方法1 判斷下標是否在容器區間內
if(currIndex >= indexLeft && currIndex <= indexRight)
    return arr[currIndex];
else
    return null; //或者拋出異常
    
//方法2 判斷下標是否超出容器區間外
if(currIndex < indexLeft || currIndex > indexRight)
    return null; //或者拋出異常
else
    return arr[currIndex];

//沒有indexRight時,方法3 判斷下標是否在容器區間內
if(currIndex >= 0 && currIndex < arr.Length)
    return arr[currIndex]; 
else
    return null;//或者拋出異常
    
//沒有indexRight時,方法4 判斷下標是否超出容器區間外
if(currIndex < 0 || currIndex >= arr.Length)
    return null; //或者拋出異常
else
    return arr[currIndex];

下標循環  ,步進加1

currIndex = currIndex < arr.Length - 1 ? currIndex + 1 : 0;
或者
currIndex = ( currIndex + 1 ) %  arr.Length;

容器類型 

order 容器名稱 鍵值
1 Array 數組 v 隨機下標訪問 快 插入刪除慢A,不支持動態擴容
2 ArrayList 動態數組 v 隨機下標訪問快 插入刪除慢A ,裝箱拆箱操作
3 List 列表 v 隨機下標訪問快 插入刪除慢A
4 SortedSet 有序哈希集 v 有序的HashSet哈希集  
5 SortedList 有序列表 kv 查找快 是排序的  
6 SortedDictionary 有序詞典 kv 二叉搜索樹 ,是排序的  
7 LinkedList 鏈表 v 增刪插入 快 訪問慢
8

HashSet  哈希集

v 插入快,集運算,求兩個集合交集、並集、差集快 不允許數據有重複,無法從特定位置訪問其中某個元素
9 Hashtable 哈希表 kv 刪除插入查找快, 裝箱拆箱操作,鍵不能出現重複
10 Dictionary 詞典 kv 查找快,鍵不能出現重複 不支持線性排序,鍵不能出現重複
11 BitArray 位集合 v    
12 Stack 堆棧 v    
13 Queue 隊列 v
14 Tree 樹  kv    
15 NameObjectCollectionBase kv   String 鍵和 Object 值的集合
16 NameValueCollection kv 鍵能出現重複,在讀取相同的key時,輸出結果對Value進行了合併  String 鍵和 String 值的集合
         
  A 從數組的中間位置刪除或插入一個元素需要付出很大的代價,其原因是數組中處於被刪除元素之後的所有元素都要向數組的前端移動。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章