I have an array which contains random integers like {2,3,4,7,8,9} . I have to retrieve 2 arrays like following which contain:
{2,3,4,7,8}(remove the last no){3,4,7,8,9}( remove the first no)
how can i do this in vb, any suggestions ?
I have an array which contains random integers like {2,3,4,7,8,9} . I have to retrieve 2 arrays like following which contain:
{2,3,4,7,8} (remove the last no){3,4,7,8,9} ( remove the first no)how can i do this in vb, any suggestions ?
Dim numbers As Int32() = {2, 3, 4, 7, 8, 9}
Dim noFirst As Int32() = numbers.Skip(1).ToArray()
Dim noLast As Int32() = numbers.Take(numbers.Length - 1).ToArray()
These are LINQ methods so you need at least .NET 3.5 and Imports System.Linq.
If you don't want to use LINQ; this is more efficient but less readable:
Dim noFirst(numbers.Length - 2) As Int32
Dim noLast(numbers.Length - 2) As Int32
Array.Copy(numbers, 1, noFirst, 0, noFirst.Length)
Array.Copy(numbers, noLast, noLast.Length)
.SkipLast(...) among many others.New String("234789".Skip(1).ToArray())"234789".Substring(1)The answer given is correct ; I'm just showing another way to achieve the same which don't suffer from the copy overhead (by use of ToArray or Array.Copy) and can be interesting in various scenarios.
Using the (underrated) ArraySegment struct (which is basically a pointer to the original array, the start offset and the count)
Dim numbers = { 2, 3, 4, 7, 8, 9 }
Dim exceptFirst = New ArraySegment(Of Int32)(numbers, 1, numbers.Length - 1)
Dim exceptLast = New ArraySegment(Of Int32)(numbers, 0, numbers.Length - 1)
As a side note, just keep in mind changes in the original array will be visible from the ArraySegment (because it's just a wrapper around it)