开发者

Combine parts of an array in VB.NET

Is there开发者_运维百科 a fast way to get all the items of an array that have even indexes and put them into a new array in VB.NET?


Whenever I see questions like this, and answers that use LINQ I always want to know how big, and how often. How big is the array and how often the code will be used. If this is something that will be used often LINQ isn't the answer.

Here is a test with a comparison of LINQ and an alternative

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Debug.WriteLine("")
    prng.NextBytes(oldArray)
    useLinq()
    useOther()
End Sub

Dim prng As New Random
Dim oldArray(131072) As Byte
Dim stpw As New Stopwatch

Private Sub useLinq()
    stpw.Restart()
    Dim newArray() As Byte = Enumerable.Range(0, oldArray.Length).Where(Function(i) i Mod 2 = 0).Select(Function(i) oldArray(i)).ToArray()
    stpw.Stop()
    Debug.WriteLine("{0} {1:n0} {2:n0} {3} {4} {5}", "L", stpw.ElapsedMilliseconds, newArray.Length, newArray(0), newArray(1), newArray(newArray.Length - 1))
End Sub

Private Sub useOther()
    stpw.Restart()
    Dim foo As New List(Of Byte)
    For x As Integer = 0 To oldArray.Length - 1 Step 2
        foo.Add(oldArray(x))
    Next
    Dim newArray() As Byte = foo.ToArray
    stpw.Stop()
    Debug.WriteLine("{0} {1:n0} {2:n0} {3} {4} {5}", "O", stpw.ElapsedMilliseconds, newArray.Length, newArray(0), newArray(1), newArray(newArray.Length - 1))
End Sub


The easiest thing to do is to do it with a for-loop but you could do something like this with linq.

Dim newArray = Enumerable.Range(0, oldArray.Length) _
                         .Where(Function(i) i Mod 2 = 0) _
                         .Select(Function(i) oldArray(i)) _
                         .ToArray()

EDIT: here's an example with byte array

Dim oldArray As Byte() = {1, 2, 3, 4, 5, 6}
Dim newArray As Byte() = Enumerable.Range(0, oldArray.Length).Where(Function(i) i Mod 2 = 0).Select(Function(i) oldArray(i)).ToArray()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜