Jake12342134
Jake12342134

Reputation: 1769

Is there a more concise way to extract (n > i) elements from an array?

I need a piece of code that is capable of taking an array of strings of length l, extracting all of the elements that are present after i, where i is a particular index less than l and then placing the extracted elements into a new array.

Essentially if we have the below:

["A", "B", "C", "D", "E", "F"]

In this instance l = 6 and if we take n = 3 then the code should create a new array

["D", "E", "F"]

I've written the code out to do this, but I can't help think there's a better, more concise way to go about it.

Here's what I have:

List<string> tempElements = new List<string>();

for (int i = startOfMessage; i < elements.Length; i++)
{
    tempElements.Add(elements[i]);
}

string[] usableMessageElements = tempElements.ToArray();

A relatively simple problem, but I'm aiming to reduce as much junior code as I can.

Upvotes: 3

Views: 275

Answers (2)

Hyarus
Hyarus

Reputation: 952

Your code looks fine but you can make use of Array.Copy:

 public string[] Extract(string[] source, int offset)
 {
        string[] strings = new string[source.Length - offset];
        Array.Copy(source, offset, strings, 0, strings.Length);
        return strings;
 }
 //...

 string[] usable = Extract(new[] { "A", "B", "C", "D", "E", "F" }, 3); //D, E, F

Not very short but faster (1,000,000 iterations):

Adding to list: 226.0038 ms

Array Copy: 107.4445 ms

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499950

It sounds like you just want to use Skip from LINQ:

string[] usableMessageElements = elements.Skip(startOfMessage).ToArray();

Upvotes: 9

Related Questions