C# Index 和 Range 類型介紹

System.Index

System.Index 表示索引,代表序列中的「第 ? 個」,先看看簡單的範例:
    
int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] arr2 = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

Index index0 = 0;
Console.WriteLine(arr1[index0]); // 1
Console.WriteLine(arr2[index0]); // 10


Index index5 = 5;
Console.WriteLine(arr1[index5]); // 6
Console.WriteLine(arr2[index5]); // 60


Index index9 = 9;
Console.WriteLine(arr1[index9]); // 10
Console.WriteLine(arr2[index9]); // 100
    

我們可以先宣告 Index ,在依照順序去取出相對應的內容。嗯...這有什麼好說的? 用 int index 不是也做得到?

比較特別的部分在於可以使用跳脫字元(caret) 來表示相對於結尾的順序,直接看範例:
    
int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] arr2 = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

Index endIndex1 = ^1;
Console.WriteLine(arr1[endIndex1]); // 10
Console.WriteLine(arr2[endIndex1]); // 100


Index endIndex5 = ^5;
Console.WriteLine(arr1[endIndex5]); // 6
Console.WriteLine(arr2[endIndex5]); // 60


Index endIndex9 = ^9;
Console.WriteLine(arr1[endIndex9]); // 2
Console.WriteLine(arr2[endIndex9]); // 20

    

我們清單的長度是 10 ,從第 0 個到第 9 個, ^0 代表的就是 arr1.Length,也就是 10 ,但不能直接找 ^0 ,因為從 0 開始,如果使用 ^0 會拋出 System.IndexOutOfRangeException 這個例外

以前我們要取 arr1 這個清單中的最後一筆內容需要這樣:
    
Console.WriteLine(arr1[arr1.Length - 1]);
    

現在我們可以替換為更簡潔的語法:
    
Console.WriteLine(arr1[^1]);
    

System.Range

System.Range 表示範圍,代表序列中的「第 ? 個到第 ? 個」,Range 是由開頭和結尾組成,在範圍中會包含開頭,但不包含結尾

再來看個簡單的範例:
    
int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] arr2 = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };


Range range = ..;
foreach (var item in arr1[range]) Console.WriteLine(item); // 1 2 3 4 5 6 7 8 9 10


Range range2 = 0..^0;
foreach (var item in arr1[range2]) Console.WriteLine(item); // 1 2 3 4 5 6 7 8 9 10

Range range2_6 = 2..6;
foreach (var item in arr1[range2_6]) Console.WriteLine(item); // 3 4 5 6

Range range2_6_2 = 2..^4;
foreach (var item in arr1[range2_6_2]) Console.WriteLine(item); // 3 4 5 6
    

留言