Category Archives: visual basic

Simple Linq Example in Visual Basic

Here is a simple example of a Linq query in Visual Basic. This code populates a list with 100 integers. It then selects all items from the list that are greater than 90 and orders that list from greatest to least. In the query portion the from t specifies that t should represent what is being selected into (which is a little confusing when it’s coupled with the “In”).

VB.Net Linq Query

        ' Delcare a list of integers (we could also use arrays, list of objects, etc).
        Dim lst As New List(Of Integer)

        ' Populate the list with 100 items
        For x As Integer = 1 To 100

        ' You don't have to include the IEnumerable but I like to see the exact definition of what
        ' something is in the code so it's crystal clear what I'm looking at.  We're going to select
        ' from the list for items above 90 and then sort those items from greatest to least.
        Dim query As IEnumerable(Of Integer) = From t In lst
                    Where t > 90
                    Order By t Descending

        For Each item As Integer In query

Visual Basic 5 & 6 INI Module

The following is a Visual Basic module to read and write from a Windows INI file. This makes use of the Windows API’s GetPrivateProfileString and WritePrivateProfileString to handle fast parsing and writing to the files.

VB Code

Attribute VB_Name = "modIni"
'  Module: INI Processing

' Windows API to read/write from the INI File
Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

Public Function GetFromIni(mySection As String, myEntry As String, iniFile As String) As String
    Dim buf As String
    Dim myLength As Long
    buf = String$(256, 0)   '256 null characters    
    myLength = GetPrivateProfileString(mySection, myEntry, "", buf, 256, iniFile)    
    getFromINI = Left$(buf, myLength)
End Function

Public Function WriteToIni(mySection As String, myEntry As String, buf As String, iniFile As String) As Boolean
    Dim x As Long
    x = WritePrivateProfileString(mySection, myEntry, buf, iniFile)

    If x = vbTrue Then
        writeToINI = True
        writeToINI = False
    End If
End Function