2

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 ?

2
  • So you want to clear values and then concatenate the 2 arrays? Commented Jun 1, 2015 at 8:00
  • no..I want only clear value and show in a loop . Commented Jun 1, 2015 at 8:07

2 Answers 2

8
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)
Sign up to request clarification or add additional context in comments.

3 Comments

It's worth adding MIcrosoft's Reactive Framework Team's "Interactive Extensions" (NuGet "Ix-Main"). You get further operators like .SkipLast(...) among many others.
@TOM: New String("234789".Skip(1).ToArray())
@TOM: in that case you can also use string methods: "234789".Substring(1)
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.