About
In this code snippet, we will take a look at ranges in C#.
Ranges give you a quick and easy syntax to get a range/interval of elements from a collection. For example, if an array has 10 elements you can specify a range from the 2nd to the 5th element and that slice of the array will be returned to you.
Let’s have a look at the code below to see how to use ranges.
Code:
string myString = "Hello World!"; //Get substring starting from 3th position on. Console.WriteLine(myString[3..]); //Get substring from start till the 3th position. Console.WriteLine(myString[..3]); //Get substring from 2rd to 5th position. Console.WriteLine(myString[2..5]); //Get substring from start to 2nd position from the end. Console.WriteLine(myString[..^2]); Console.WriteLine(""); //The same thing can be applied to arrays. int[] myArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] myArrayPart = null; myArrayPart = myArray[3..]; myArrayPart.ToList().ForEach(x => Console.Write(x)); Console.WriteLine(); myArrayPart = myArray[..3]; myArrayPart.ToList().ForEach(x => Console.Write(x)); Console.WriteLine(); myArrayPart = myArray[2..5]; myArrayPart.ToList().ForEach(x => Console.Write(x)); Console.WriteLine(); myArrayPart = myArray[..^2]; myArrayPart.ToList().ForEach(x => Console.Write(x)); Console.WriteLine(); Console.ReadLine();