OneBite.Dev - Coding blog in a bite size

Extract A Sub-Array From An Array In C#

Code snippet for how to Extract A Sub-Array From An Array In C# with sample and detail explanation

Extracting a subarray from an array in C# is a fundamental skill to master in programming as it can be used in various scenarios like data manipulation, sorting, and analyzing. This article will guide you through a simple step-by-step process of accomplishing this task effortlessly using a simple C# code snippet.

Code snippet for Extracting a Sub-Array from an Array

Let’s start with creating a simple code block that demonstrates how to extract a subarray from an array in C#. Below is a simple implementation.

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int start = 2;
        int length = 4;

        int[] subArray = array.Skip(start).Take(length).ToArray();

        Console.WriteLine(string.Join(", ", subArray));
    }
}

Code Explanation for Extracting a Sub-Array from an Array

Here is a step-by-step explanation of the C# code snippet provided above:

  1. Import the necessary namespaces: We import the System and System.Linq namespaces which contain the necessary classes and methods we will use.
using System;
using System.Linq;
  1. Define the Main method: This is the entry point of our application.
static void Main(string[] args)
  1. Define the original array: We initialize an array of integers named ‘array’ with 9 elements.
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  1. Define the start and length variables: In this example, we want to start from the third element (index 2) and take 4 elements.
int start = 2;
int length = 4;
  1. Extract the sub-array: We use the ‘Skip’ method to skip the first ‘start’ elements and then ‘Take’ the next ‘length’ elements. Finally, we convert the result back to an array using ‘ToArray’.
int[] subArray = array.Skip(start).Take(length).ToArray();
  1. Display the sub-array: We use ‘Console.WriteLine’ to print our sub-array to the console. Here, ‘Join’ method is used to convert the array into a string, separating each element by a comma.
Console.WriteLine(string.Join(", ", subArray));

After running this program, it should display 3, 4, 5, 6, which are the third to the sixth elements of the original array.

And that’s it! That’s how you extract a sub-array from an array in C#. Remember that the ‘Skip’ and ‘Take’ methods operate on zero-based indices.

c-sharp