C# Collections' index and range operators

Index operator ^1

The index operator is used to reach the last positions of an array or list.

before

List<int> arr = [0, 1, 2, 3, 4, 5];
if(arr[arr.Count-1] == 5)
	Console.WriteLine("match!"); // prints

same but using index operator

List<int> arr = [0, 1, 2, 3, 4, 5];
if(arr[^1] == 5)
	Console.WriteLine("match!"); // prints

we can use it to reach any position starting from the back

List<int> arr = [0, 1, 2, 3, 4, 5];
if(arr[^2] == 4)
	Console.WriteLine("match!"); // prints

Range operator ..

The range operator is used to make a slice of a collection

  • start of the range is inclusive
  • end of the range is exclusive

sample .. means range of all elements

List<int> arr = [0, 1, 2, 3, 4, 5];
var subList = arr[..];
foreach(var item in subList)
	Console.Write(item); // 0 1 2 3 4 5

whole range

List<int> arr = [0, 1, 2, 3, 4, 5];
var subList = arr[1..3];
foreach(var item in subList)
	Console.Write(item); // 1 2

we may omit the start or the end

List<int> arr = [0, 1, 2, 3, 4, 5];
var subList = arr[..3];
foreach(var item in subList)
	Console.Write(item); // 0 1 2
List<int> arr = [0, 1, 2, 3, 4, 5];
var subList = arr[2..];
foreach(var item in subList)
	Console.Write(item); // 2 3 4 5

Mixing index and range operators

Both operators can be mixed to set a limit by the back of the list

List<int> arr = [0, 1, 2, 3, 4, 5];
var subList = arr[1..^1];
foreach(var item in subList)
	Console.Write(item); // 1 2 3 4
List<int> arr = [0, 1, 2, 3, 4, 5];
var subList = arr[..^2];
foreach(var item in subList)
	Console.Write(item); // 0 1 2 3