VB.Net/Data Structure/Collection

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

Database Connection state change event

<source lang="vbnet"> Imports System Imports System.Data Imports System.Data.SqlClient

public class MainClass

  Shared Sub Main()
     Dim thisConnection As New SqlConnection("server=(local)\SQLEXPRESS;" & _
         "integrated security=sspi;database=MyDatabase")
     " Sql Query
     Dim sql As String = "SELECT FirstName, LastName From Employee"
     " Create command
     Dim thisCommand As New SqlCommand(sql, thisConnection)
     " Add second handler to StateChange event
     AddHandler thisConnection.StateChange, AddressOf StateIsChanged
     Try
        " Open connection and fire two statechange events
        thisConnection.Open()
        " Create datareader
        Dim thisReader As SqlDataReader = thisCommand.ExecuteReader()
        " Display rows in event log
        While thisReader.Read()
           Console.WriteLine(thisReader.GetString(0) _
              + "-" + thisReader.GetString(1))
        End While
     Catch ex As SqlException
        Console.WriteLine(ex.Message)
     Finally
        " Remove second handler from StateChange event
        RemoveHandler thisConnection.StateChange, AddressOf StateIsChanged
        " Close connection and fire one StateChange event
        thisConnection.Close()
     End Try
  End Sub
  Shared Private Sub StateIsChanged(ByVal sender As Object, ByVal e As System.Data.StateChangeEventArgs)
     " Event handler for the StateChange Event
     Console.WriteLine("Entering Second StateChange EventHandler")
     Console.WriteLine("Sender = " + sender.ToString())
     Console.WriteLine("Original State = " + e.OriginalState.ToString())
     Console.WriteLine("Current State = " + e.CurrentState.ToString())
     Console.WriteLine("Exiting Second StateChange EventHandler")
  End Sub

End Class

      </source>


Do While loop through a Collection

<source lang="vbnet"> Imports System Imports System.Collections Public Class MainClass

   Shared Sub Main(ByVal args As String())
       Dim m_Employees As New Collection
       m_Employees.Add(New Employee("A"))
       m_Employees.Add(New Manager("B"))
       m_Employees.Add(New Manager("C"))
       m_Employees.Add(New Employee("D"))
       Dim emp As Employee
       Dim employee_enumerator As IEnumerator
       
       employee_enumerator = m_Employees.GetEnumerator()
       
       Do While (employee_enumerator.MoveNext)
           emp = CType(employee_enumerator.Current, Employee)
           Console.WriteLine( emp.Name )
       Loop
   End Sub

End Class

Public Class Employee

   Public Name As String
   Public Sub New(ByVal new_name As String)
       Name = new_name
   End Sub
   Public Overridable Function IsManager() As Boolean
       Return False
   End Function

End Class Public Class Customer

   Public Name As String
   Public Sub New(ByVal new_name As String)
       Name = new_name
   End Sub

End Class Public Class Manager

   Inherits Employee
   Public Sub New(ByVal new_name As String)
       MyBase.new(new_name)
   End Sub
   Public Overrides Function IsManager() As Boolean
       Return True
   End Function

End Class

      </source>


For Each loop through a Collection

<source lang="vbnet"> Imports System Imports System.Collections Public Class MainClass

   Shared Sub Main(ByVal args As String())
       Dim people As New Collection
       people.Add(New Employee("A"))
       people.Add(New Customer("B"))
       " Works.
       For Each person As Object In people
           Console.WriteLine(person.Name)
       Next person
   End Sub

End Class

Public Class Employee

   Public Name As String
   Public Sub New(ByVal new_name As String)
       Name = new_name
   End Sub
   Public Overridable Function IsManager() As Boolean
       Return False
   End Function

End Class Public Class Customer

   Public Name As String
   Public Sub New(ByVal new_name As String)
       Name = new_name
   End Sub

End Class Public Class Manager

   Inherits Employee
   Public Sub New(ByVal new_name As String)
       MyBase.new(new_name)
   End Sub
   Public Overrides Function IsManager() As Boolean
       Return True
   End Function

End Class

      </source>


Loop through Collection

<source lang="vbnet"> Imports System Imports System.Collections Public Class MainClass

   Shared Sub Main(ByVal args As String())
       Dim m_employees As New Collection
       m_employees.Add(New employee("A", "B", "Author"))
       m_employees.Add(New employee("C", "D", "Band"))
       m_employees.Add(New employee("E", "F", "Artist"))
       " Iterator.
       Dim emp As employee
       Dim employee_enumerator As IEnumerator
       employee_enumerator = m_employees.GetEnumerator()
       Do While (employee_enumerator.MoveNext)
           emp = CType(employee_enumerator.Current, Employee)
           Console.WriteLine(emp.Title & " " & emp.FirstName & " " & emp.LastName)
       Loop
       " For Each.
       For Each emp1 As employee In m_employees
           Console.WriteLine(emp1.Title & " " & emp1.FirstName & " " & emp1.LastName)
       Next emp1
   End Sub

End Class

   Public Class Employee
       Public FirstName As String
       Public LastName As String
       Public Title As String
       Public Sub New(ByVal first_name As String, ByVal last_name As String, ByVal new_title As String)
           FirstName = first_name
           LastName = last_name
           Title = new_title
       End Sub
   End Class


      </source>


Store Class in a Collection and Retrieve by Name

<source lang="vbnet"> Imports System Imports System.Collections

Public Class MainClass

   Shared Sub Main(ByVal args As String())
                
            Dim intCollection As New Collection( )
            Dim empCollection As New Collection( )
            Dim empCollection2 As New Collection( )
            " populate the Collections
            Dim i As Integer
            For i = 0 To 4
                empCollection.Add(New EnumerableClass("A", "B"))
                intCollection.Add((i * 5))
            Next i
            " add key/value pairs
            empCollection2.Add(New EnumerableClass("A", "B"), "A B")
            empCollection2.Add(New EnumerableClass("C", "D"), "C D")
            empCollection2.Add(New EnumerableClass("E", "F"), "E F")
            " print each member of the array
            For Each i In intCollection
                Console.Write("{0} ", i.ToString( ))
            Next i
            Console.WriteLine( )
            Console.WriteLine("Employee collection...")
            Dim e As EnumerableClass
            For Each e In empCollection
                Console.Write("{0} ", e.ToString( ))
            Next e
            Console.WriteLine( )
            Console.WriteLine("Employee collection 2...")
            For Each e In empCollection2
                Console.Write("{0} ", e.ToString( ))
            Next e
            Console.WriteLine( )
            " retrieve an Employee by key
            Dim emp As EnumerableClass
            emp = empCollection2.Item("A B")
            Console.WriteLine( _
              " empID {0}", emp.ToString( ))
            " note that indexing is 1-based (rather than zero based)
            emp = empCollection2.Item(1)
            Console.WriteLine( _
              "Index(1) retrieved empID {0}", emp.ToString( ))
   End Sub

End Class

    Public Class EnumerableClass : Implements IEnumerable
        Private strings( ) As String
        Private ctr As Integer = 0
        Private Class MyEnumerator
            Implements IEnumerator
            Private currentListBox As EnumerableClass
            Private index As Integer
            Public Sub New(ByVal currentListBox As EnumerableClass)
                Me.currentListBox = currentListBox
                index = -1
            End Sub
            Public Function MoveNext( ) As Boolean _
              Implements IEnumerator.MoveNext
                index += 1
                If index >= currentListBox.strings.Length Then
                    Return False
                Else
                    Return True
                End If
            End Function
            Public Sub Reset( ) _
              Implements IEnumerator.Reset
                index = -1
            End Sub
            Public ReadOnly Property Current( ) As Object _
            Implements IEnumerator.Current
                Get
                    Return currentListBox(index)
                End Get
            End Property
        End Class  " end nested class
        Public Function GetEnumerator( ) As IEnumerator _
        Implements IEnumerable.GetEnumerator
            Return New MyEnumerator(Me)
        End Function
        Public Sub New( _
          ByVal ParamArray initialStrings( ) As String)
            ReDim strings(7)
            Dim s As String
            For Each s In initialStrings
                strings(ctr) = s
                ctr += 1
            Next
        End Sub
        Public Sub Add(ByVal theString As String)
            strings(ctr) = theString
            ctr += 1
        End Sub
        Default Public Property Item( _
          ByVal index As Integer) As String
            Get
                If index < 0 Or index >= strings.Length Then
                    " handle bad index
                    Exit Property
                End If
                Return strings(index)
            End Get
            Set(ByVal Value As String)
                strings(index) = Value
            End Set
        End Property
        Public Function GetNumEntries( ) As Integer
            Return ctr
        End Function
    End Class


      </source>


Store Objects in Collection and retrieve

<source lang="vbnet"> Imports System Imports System.Collections Public Class MainClass

   Shared Sub Main()
      Dim intCollection As New Collection(  )
      Dim empCollection As New Collection(  )
      Dim empCollection2 As New Collection(  )
 
      "populate the Collections
      Dim i As Integer
      For i = 0 To 4
          empCollection.Add(New Employee(i + 100))
          intCollection.Add((i * 5))
      Next i
 
      "add key/value pairs
      empCollection2.Add(New Employee(1989), "G W")
      empCollection2.Add(New Employee(1997), "J A")
      empCollection2.Add(New Employee(1901), "T J")
 
 
      "print each member of the array
      For Each i In intCollection
          Console.Write("{0} ", i.ToString(  ))
      Next i
 
      Console.WriteLine(  )
      Console.WriteLine("Employee collection...")
      Dim e As Employee
      For Each e In empCollection
          Console.Write("{0} ", e.ToString(  ))
      Next e
 
      Console.WriteLine(  )
      Console.WriteLine("Employee collection 2...")
      For Each e In empCollection2
          Console.Write("{0} ", e.ToString(  ))
      Next e
 
      Console.WriteLine(  )
 
      "retrieve an Employee by key
      Dim emp As Employee
      emp = empCollection2.Item("J A")
      Console.WriteLine( emp.ToString(  ))
 
      "note that indexing is 1-based (rather than zero based)
      emp = empCollection2.Item(1)
      Console.WriteLine(emp.ToString(  ))
  End Sub

End Class

    Public Class Employee
        Private myEmpID As Integer
        Public Sub New(ByVal empID As Integer)
            Me.myEmpID = empID
        End Sub "New
        Public Overrides Function ToString(  ) As String
            Return myEmpID.ToString(  )
        End Function "ToString
        Public Property EmpID(  ) As Integer
            Get
                Return myEmpID
            End Get
            Set(ByVal Value As Integer)
                myEmpID = Value
            End Set
        End Property
    End Class "Employee
          
      </source>