Extract Part Of A String Array In C#

Introduction

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.

Extract part of string array in CSharp

One way to achieve this is, 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.

namespace System
{
    public struct Range: IEquatable<Range>
    {
        public Index End { get; }
        public Index Start { get; }
        public static Range All();
        public static Range Create(Index start, Index end);
        public static Range FromStart(Index start);
        public static Range ToEnd(Index end);
        public override bool Equals(object value);
        public bool Equals(Range other);
        public override int GetHashCode();
        public override string ToString();
    }
}

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 define 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];

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

// Array of scores
int[] scores = { 1, 9, 11, 90, 101, 199, 201, 499, 501, 1000, 1001, 1999, 2001, 4999 };
// Get scores from the 6th item to the next 5
Range range = Range.Create(5, 10);
var myScores = scores[range];
// Read scores
foreach (int score in myScores)
{
    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 the Solution Explorer Properties Build Advanced Language version drop-down and select version C# 8.0 (beta) from the drop-down.


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.