VB.Net Tutorial/Collections/Array

Материал из VB Эксперт
Перейти к: навигация, поиск

Array Clone

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
       Dim arrayA() As String = {"One", "Two", "Three", "Four", "Five", "Six"}
       Console.WriteLine(Join(arrayA, ","))
       Dim arrayB() As String = {"A", "B", "C", "D", "E", "E", "F", "G", "H"}
       Console.WriteLine(Join(arrayB, ","))
       " ----- Make a reference copy.
       Dim arrayC() As String = arrayA
       Console.WriteLine(Join(arrayC, ","))
       " ----- Make a full, unique copy of all elements.
       Dim arrayD() As String = arrayA.Clone
       Console.WriteLine(Join(arrayD, ","))
   End Sub

End Class</source>

One,Two,Three,Four,Five,Six
A,B,C,D,E,E,F,G,H
One,Two,Three,Four,Five,Six
One,Two,Three,Four,Five,Six

Array declaration

<source lang="vbnet">Option Strict On Public Module Arrays

  Public Sub Main
     Dim arr As Array
     Dim int() As Integer = {12, 16, 20, 24, 28, 32}
     arr = CType(int, Array)
     Dim byFours() As Integer = {12, 24, 36, 48}
     Dim names() As String = {"K", "S", "S", "D", "N"}
     Dim miscData() As Object = {"this", 12d, 16ui, "a"c}
     Dim objArray() As Object
     miscData = names
     
     Dim myArray1a() As Integer " Uninitialized array
     Dim myArray1b As Integer() " Uninitialized array
     Dim myArray2(10) As Integer " 1-dimensional array with 11 elements
     Dim Employees1( , ) As Object " Uninitialized 2-D array
     Dim Employees(200, 2) As Object " 2-D array with 201 and 3 elements
     Dim jagged1(9)() As String
     Dim jagged2()() As String = New String(9)() {}
     Dim myArray1arr As Array
     Dim myArray2a As Array = Array.CreateInstance(GetType(Integer), 10)
     Dim members() As Integer = {3, 10}
     Dim myArray3a As Array = Array.CreateInstance(GetType(Integer), members)
  End Sub

End Module</source>

Array length: negative

<source lang="vbnet">Option Strict On Public Module ValidArray

  Public Sub Main()
     Dim emptyArray(-1) As String
     For Each element As String In emptyArray
        Console.WriteLine(element)
     Next
  End Sub

End Module</source>

Array Resize

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
       Dim result As New System.Text.StringBuilder
       Dim arrayInsert() As String = {"O", "A", "G", "B", "B"}
       " ----- Show the contents before insertion.
       result.AppendLine("Before insertion:")
       For Each fruit As String In arrayInsert
           result.AppendLine(fruit)
       Next fruit
       " ----- Insert more fruit.
       InsertArrayElement(Of String)(arrayInsert, 2, "Lemons")
       " ----- Show the contents after insertion.
       result.AppendLine()
       result.AppendLine("After insertion:")
       For Each fruit As String In arrayInsert
           result.AppendLine(fruit)
       Next fruit
       Console.WriteLine(result.ToString())
   End Sub
   Public Shared Sub InsertArrayElement(Of T)( _
         ByRef sourceArray() As T, _
         ByVal insertIndex As Integer, _
         ByVal newValue As T)
       Dim newPosition As Integer
       Dim counter As Integer
       newPosition = insertIndex
       If (newPosition < 0) Then newPosition = 0
       If (newPosition > sourceArray.Length) Then _
          newPosition = sourceArray.Length
       Array.Resize(sourceArray, sourceArray.Length + 1)
       For counter = sourceArray.Length - 2 To newPosition Step -1
           sourceArray(counter + 1) = sourceArray(counter)
       Next counter
       sourceArray(newPosition) = newValue
   End Sub

End Class</source>

Before insertion:
O
A
G
B
B
After insertion:
O
A
Lemons
G
B
B

Assing array element value by using index

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim arySalaries(15) As Integer
       Dim aryNames(15) As String
       Dim intCounter As Integer
       aryNames(0) = "J"
       arySalaries(0) = 34000
       aryNames(1) = "B"
       arySalaries(1) = 62000
       "Set other array elements here.
       aryNames(15) = "P"
       arySalaries(15) = 10300
       "Show the elements of the array.
       For intCounter = 0 To 15
           Console.WriteLine("Array element: " & intCounter & vbCrLf & _
                  "Name: " & aryNames(intCounter) & vbCrLf & _
                  "Salary: " & arySalaries(intCounter))
       Next intCounter
  End Sub

End class</source>

Array element: 0
Name: J
Salary: 34000
Array element: 1
Name: B
Salary: 62000
Array element: 2
Name:
Salary: 0
Array element: 3
Name:
Salary: 0
Array element: 4
Name:
Salary: 0
Array element: 5
Name:
Salary: 0
Array element: 6
Name:
Salary: 0
Array element: 7
Name:
Salary: 0
Array element: 8
Name:
Salary: 0
Array element: 9
Name:
Salary: 0
Array element: 10
Name:
Salary: 0
Array element: 11
Name:
Salary: 0
Array element: 12
Name:
Salary: 0
Array element: 13
Name:
Salary: 0
Array element: 14
Name:
Salary: 0
Array element: 15
Name: P
Salary: 10300

Computing sum of elements in array.

<source lang="vbnet">Module Tester

  Sub Main()
     Dim array As Integer() = New Integer() _
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
     Dim total As Integer = 0, i As Integer = 0
     For i = 0 To array.GetUpperBound(0)
        total += array(i)
     Next
     Console.WriteLine("Total of array elements: " & total)
  End Sub 

End Module</source>

Total of array elements: 55

Declaring and allocating an array

<source lang="vbnet">Module Tester

  Sub Main()
     Dim i As Integer
     Dim array As Integer()    " declare array variable
     array = New Integer(9) {} " allocate memory for array
     Console.WriteLine("Subscript " & vbTab & "Value")
     For i = 0 To array.GetUpperBound(0)
        Console.WriteLine( i & vbTab & array(i))
     Next
     Console.WriteLine("The array contains " & _
        array.Length & " elements.")
  End Sub 
  

End Module</source>

Subscript       Value
0       0
1       0
2       0
3       0
4       0
5       0
6       0
7       0
8       0
9       0
The array contains 10 elements.

Display the contents of a single-dimension array

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
       Dim sourceArray() As Integer = {1, 2, 3}
       Dim result As New System.Text.StringBuilder
       Dim counter As Integer
       result.Append("{")
       For counter = 0 To sourceArray.Length - 1
           result.Append(sourceArray(counter).ToString())
           If (counter < (sourceArray.Length - 1)) Then result.Append(",")
       Next counter
       result.Append("}")
       Console.WriteLine(result.ToString())
       
   End Sub

End Class</source>

{1,2,3}

Initialize Array element during declaration

<source lang="vbnet">Option Strict On

Imports System
Public Class Employee
    Private empID As Integer
    Public Sub New(ByVal empID As Integer)
        Me.empID = empID
    End Sub 
    Public Overrides Function ToString( ) As String
        Return empID.ToString( )
    End Function 
End Class 

Class Tester

    Public Shared Sub Main( )
        Dim intArray As Integer( ) = {2, 4, 6, 8, 10}
        Dim empArray As Employee( ) = _
          {New Employee(5), New Employee(7), New Employee(9)}
   
        Console.WriteLine("The Integer array...")
        Dim theInt As Integer
        For Each theInt In intArray
            Console.WriteLine(theInt.ToString( ))
        Next theInt
   
        Console.WriteLine("The employee array...")
        Dim e As Employee
        For Each e In empArray
            Console.WriteLine(e.ToString( ))
        Next e
    End Sub "Run
End Class</source>
The Integer array...
2
4
6
8
10
The employee array...
5
7
9

Initializing arrays

<source lang="vbnet">Module Tester

  Sub Main()
     Dim i As Integer
     Dim array1, array2 As Integer() " declare two arrays
     " initializer list specifies number of elements
     " and value of each element
     array1 = New Integer() {2, 7, 4, 8, 5, 14, 90, 70, 60, 37}
     " allocate array2 based on length of array1
     array2 = New Integer(array1.GetUpperBound(0)) {}
     " set values in array2 by a calculation
     For i = 0 To array2.GetUpperBound(0)
        array2(i) = 2 + 2 * i
     Next
     Console.WriteLine("Subscript " & vbTab & "Array1" & vbTab & _
        "Array2")
     " display values for both arrays
     For i = 0 To array1.GetUpperBound(0)
        Console.WriteLine(i & vbTab & array1(i) & vbTab & array2(i))
     Next
  End Sub 

End Module</source>

Subscript       Array1  Array2
0       2       2
1       7       4
2       4       6
3       8       8
4       5       10
5       14      12
6       90      14
7       70      16
8       60      18
9       37      20

Insert element in the middle of an Array

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
       Dim result As New System.Text.StringBuilder
       Dim arrayInsert() As String = {"O", "A", "G", "B", "B"}
       " ----- Show the contents before insertion.
       result.AppendLine("Before insertion:")
       For Each fruit As String In arrayInsert
           result.AppendLine(fruit)
       Next fruit
       " ----- Insert more fruit.
       InsertArrayElement(Of String)(arrayInsert, 2, "Lemons")
       " ----- Show the contents after insertion.
       result.AppendLine()
       result.AppendLine("After insertion:")
       For Each fruit As String In arrayInsert
           result.AppendLine(fruit)
       Next fruit
       Console.WriteLine(result.ToString())
   End Sub
   Public Shared Sub InsertArrayElement(Of T)( _
         ByRef sourceArray() As T, _
         ByVal insertIndex As Integer, _
         ByVal newValue As T)
       Dim newPosition As Integer
       Dim counter As Integer
       newPosition = insertIndex
       If (newPosition < 0) Then newPosition = 0
       If (newPosition > sourceArray.Length) Then _
          newPosition = sourceArray.Length
       Array.Resize(sourceArray, sourceArray.Length + 1)
       For counter = sourceArray.Length - 2 To newPosition Step -1
           sourceArray(counter + 1) = sourceArray(counter)
       Next counter
       sourceArray(newPosition) = newValue
   End Sub

End Class</source>

Before insertion:
O
A
G
B
B
After insertion:
O
A
Lemons
G
B
B

One dimesional array performance

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim start_time As DateTime
       Dim stop_time As DateTime
       Dim elapsed_time As TimeSpan
       Dim num_items As Integer = 10000
       Dim array1(0 To num_items - 1) As Integer
       start_time = Now
       For i As Integer = 0 To num_items - 1
           array1(i) = i
       Next i
       stop_time = Now
       elapsed_time = stop_time.Subtract(start_time)
       Console.WriteLine(elapsed_time.TotalSeconds())
       Erase array1
  End Sub
  

End class</source>

0

Reorder the elements of an array in a random order

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
       Dim arrayShuffle() As String = {"A", "B", "C", "D", "E"}
       For Each fruit As String In arrayShuffle
           Console.WriteLine(fruit)
       Next fruit
       Shuffle(arrayShuffle)
       For Each fruit As String In arrayShuffle
           Console.WriteLine(fruit)
       Next fruit
   End Sub
   Public Shared Sub Shuffle(ByRef shuffleArray() As Object)
       Dim counter As Integer
       Dim newPosition As Integer
       Dim shuffleMethod As New Random
       Dim tempObject As Object
       For counter = 0 To shuffleArray.Length - 1
           newPosition = shuffleMethod.Next(0, shuffleArray.Length - 1)
           tempObject = shuffleArray(counter)
           shuffleArray(counter) = shuffleArray(newPosition)
           shuffleArray(newPosition) = tempObject
       Next counter
   End Sub

End Class</source>

A
B
C
D
E
B
A
E
C
D

Swap elements in an array

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
       Dim result As New System.Text.StringBuilder
       Dim arraySwap() As String = {"A", "B", "C", "D", "E"}
       Swap(arraySwap, 1, 3)
       For Each fruit As String In arraySwap
           Console.WriteLine(fruit)
       Next fruit
   End Sub
   Public Shared Sub Swap(ByRef swapArray() As Object, _
           ByVal first As Integer, ByVal second As Integer)
       Dim tempObject As Object
       tempObject = swapArray(first)
       swapArray(first) = swapArray(second)
       swapArray(second) = tempObject
   End Sub

End Class</source>

A
D
C
B
E

Two dimesional array performance

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim start_time As DateTime
       Dim stop_time As DateTime
       Dim elapsed_time As TimeSpan
       Dim num_items As Integer = 10000
       " Two-dimensional array.
       Dim array2(0 To 0, 0 To num_items - 1) As Integer
       start_time = Now
       For i As Integer = 0 To num_items - 1
           array2(0, i) = i
       Next i
       stop_time = Now
       elapsed_time = stop_time.Subtract(start_time)
       Console.WriteLine(elapsed_time.TotalSeconds())
       Erase array2
  End Sub
  

End class</source>

0

Use For loop to initialize Integer array

<source lang="vbnet">Module Module1

   Sub Main()
       Dim Students(50) As Integer
       Dim I As Integer
       For I = 0 To 50
           Students(I) = I
       Next
       For I = 0 To 50
           Console.WriteLine(Students(I))
       Next
   End Sub

End Module</source>

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50