Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sub-array from larger array in VB.NET?

I have:

Dim arr() As String = {"one","two","three"}

I want a new array, sub, containing {"one", "three"} only. What is the best method to do this?

like image 787
Yugal Jindle Avatar asked Dec 27 '22 16:12

Yugal Jindle


1 Answers

For this particular case, the simplest option is just to list the two items you want to copy:

Dim sub = {arr(0), arr(2)}

In the general case, if you want to take the first item, skip one item, and then take all the rest, an easy option would be to use the LINQ extension methods:

Dim sub = arr.Take(1).Concat(arr.Skip(2)).ToArray()

It yields

  • {"one"} (arr.Take(1))
  • concatenated with (Concat)
  • {"three"} (arr.Skip(2))
  • into a new array (ToArray())

Documentation:

  • Enumerable.Take
  • Enumerable.Skip
like image 137
Heinzi Avatar answered Dec 30 '22 10:12

Heinzi