Markdown Extract Part of a String Array in C#

Recently, in one of my projects, I needed to get a portion of a string[] array. To be exact, I needed to get 5 items following the nth item in the array.

One way to achieve this is, I could use an array index and read one item at a time. What if you need to read 100 or 1000 items? That would be a messy code.

Now, C# 8.0 provides an efficient and cleaner way to get a portion of an array by using a range. The range is defined by a Range struct type.

The Range Structure

The Range struct in C# provides a way to create a range that could be passed in an array to get the items that fall in that range.

The following code is the Range struct definition

  1. namespace System
  2. {
  3. public struct Range : IEquatable<Range>
  4. {
  5. public Index End { get; }
  6. public Index Start { get; }
  7. public static Range All();
  8. public static Range Create(Index start, Index end);
  9. public static Range FromStart(Index start);
  10. public static Range ToEnd(Index end);
  11. public override bool Equals(object value);
  12. public bool Equals(Range other);
  13. public override int GetHashCode();
  14. public override string ToString();
  15. }
  16. }

The Range.Create() method is used to create a Range. We can also pass start and end index in the Create method. The Start and End Index types defines the from and to positions of the range.

The following code snippet creates a Range starting at position 5 (6th item) to 10.

Range range = Range.Create(5, 10);

Now, we can pass a Range variable in an array to get the items that fall in this range.

var myScores = scores[range];

Alternatively, we can also pass a range like this:

var myScores = scores[5..10];

C# Code Example

The following code snippet is a complete code sample of use of a Range struct in C#.

  1. // Array of scores
  2. int[] scores = { 1, 9, 11, 90, 101, 199, 201, 499, 501, 1000, 1001, 1999, 2001, 4999 };
  3. // Get scores from 5th item to next 5
  4. Range range = Range.Create(5, 10);
  5. var myScores = scores[range];
  6. // Read scores
  7. foreach (int score in myScores)
  8. Console.WriteLine(score);

Learn more on Index type in C# here:

C# Index Type

This feature is available in C# 8 or later versions only. If you’re running the previous versions of Visual Studio 2019, you need to install C# 8.0. If you’re running Visual Studio 2019, you can set the language version of your project by setting Advanced Build Settings.

To get to the Advanced Build Properties, right click on the project name in Solution Explorer > Properties > Build > Advanced > Language version drop down and select version C# 8.0 (beta) from the drop down.

Similar Articles
test
nothing