Tag Archives: list

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
            lst.Add(x)
        Next

        ' 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
            Console.WriteLine(item)
        Next