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

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

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?

回答1:

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:



回答2:

You can use the Array.Copy method. I don't know how you are picking elements from your array. Are you randomly picking or any other way? But I think you need to create a second array and use the Copy method.

You can use the Copy method in a variety of ways. The link I gave above is to pick an element from a specified index of the first array and copy to a specified index of the second array.

Here is an example in C#:

string[] firstArray = {"dog","cat","fish","monkey"}; string[] secondArray = firstArray; Array.Copy(firstArray,3,secondArray,0,1); Console.WriteLine(secondArray[0].ToString()); 

A VB.NET example is here:

Arrays: Copy vs. Clone

In your case, you can put the Array.Copy in a loop and keep changing the source and destination index.



回答3:

It's a little difficult to see what you want exactly, but something like this will work.

Dim arr() As String = {"one","two","three"}  Dim templist As New List(Of String)(arr) templist.RemoveAt(1) Dim sub() As String = templist.ToArray() 

Personally, I'd be using List rather than String() if you want to make frequent changes like this.


EDIT: Considering RPK's comment below:

Function RemoveElements(ByVal arr() As String, ByVal ParamArray skip() As Integer) As String()     Dim templist As New List(Of String)(arr.Length - skip.Length)     For i As Integer = 0 to templist.Length - 1         if Array.IndexOf(skip, i) = -1 Then templist.Add(arr(i))     Next i     Return templist.ToArray() End Function 

You can call this for a single element:

' Skips the second element. Dim sub() As String = RemoveElements(arr, 1) 

or with as many elements as you like:

' Skips the second, fourth, seventh and eleventh elements. Dim sub() As String = RemoveElements(arr, 1, 3, 6, 10) 

or with an array:

' Skips the second, fourth, seventh and eleventh elements. Dim skip() As Integer = {1, 3, 6, 10} Dim sub() As String = RemoveElements(arr, skip) 

Note, this is slow code, but it can make your code easier to read and maintain.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!