Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Substring Equivalent of array [duplicate]

Is there a substring equivalent for an array?

Input new char[] foo = {'a', 'b', 'c', 'd', 'e', 'f'}

If this was a String abcdef I would use .Substring(0, 2) and get ab

Is there a built in method that would give me char[] {'a', 'b'} if the input indexes were 0, 2?

Code Example

char[] foo = {'a', 'b', 'c', 'd', 'e', 'f'};
char[] bar = foo.**Method**(0, 2); //what can I do here?

Console.WriteLine(bar);
//Output would be` **ab**

I know I could just convert the Char array back to a String, use Substring and back to a Char Array. But that would take some extra lines of Code and I want to know, if it is possible with only 1 built-in Method.

like image 700
eventseen Avatar asked Jan 03 '23 17:01

eventseen


1 Answers

There isn't a single method for this but you can use Linq to get the same affect like

var newArr = set.Skip(n).Take(k).ToArray();

Further step could be writing an extension method

public static class MyExtensions
{
    public static T[] Subsequence<T>(this IEnumerable<T> arr,int startIndex, int length)
    {
        return arr.Skip(startIndex).Take(length).ToArray();
    }
}

and use it as

var newset = new[] { 1, 2, 3, 4, 5 }.Subsequence(1, 2);
like image 100
L.B Avatar answered Jan 16 '23 18:01

L.B