Working with many things at once
Business software is mostly about collections: the orders of the day, the stock in a warehouse, the students in a class, the lines of an invoice. Classic Visual Basic offered arrays and a general-purpose Collection object, and programs spent many lines resizing arrays and looping through them. Visual Basic .NET has the full set of .NET collections, and since 2008 it has had LINQ, which lets you ask questions of a collection in a few readable lines: "which regions harvested maize, largest first?", "how many tonnes of each crop?".
Visual Basic's version of LINQ is, if anything, richer than C#'s, with extra query keywords such as Aggregate, Distinct, Skip and Take. And Visual Basic has a feature that very few languages have ever offered: XML literals, which let you write XML directly in your code and query it with a special syntax. Both are common in Visual Basic code from the last fifteen years, so a maintainer needs to read them fluently.
Lists, dictionaries and sets
The generic collections live in System.Collections.Generic, which Visual Basic projects import automatically. In Visual Basic, type arguments are written with Of: List(Of String), Dictionary(Of String, Integer).
Option Strict On
Module Program
Sub Main()
' List(Of T): a growable list. From {...} is a collection initializer.
Dim queue As New List(Of String) From {"Amara", "Bao", "Chiara"}
queue.Add("Dmitri")
queue.Insert(0, "Yusuf")
queue.Remove("Bao")
Console.WriteLine($"{queue.Count} waiting: {String.Join(", ", queue)}; first is {queue(0)}")
' Dictionary(Of TKey, TValue): look up by key.
Dim stock As New Dictionary(Of String, Integer) From {{"rice", 20}, {"beans", 12}}
stock("salt") = 5 ' add or replace
stock("rice") -= 3
Dim lentils As Integer
If Not stock.TryGetValue("lentils", lentils) Then
Console.WriteLine("no lentils in stock")
End If
For Each entry In stock
Console.WriteLine($"{entry.Key,-6} {entry.Value,3}")
Next
' HashSet(Of T): each value once; fast membership tests.
Dim seen As New HashSet(Of String)
For Each word In "the river and the road and the river bend".Split(" "c)
If Not seen.Add(word) Then Console.Write($"[repeat: {word}] ")
Next
Console.WriteLine()
Console.WriteLine($"{seen.Count} distinct words")
' Legacy code resizes arrays with ReDim Preserve; a List does this for you.
Dim readings(2) As Double
readings(0) = 1.5 : readings(1) = 2.5 : readings(2) = 3.5
ReDim Preserve readings(4)
readings(3) = 4.5
Console.WriteLine($"{readings.Length} slots: {String.Join(" ", readings)}")
' A two-dimensional array: a seating plan of 2 rows and 3 seats.
Dim seats(1, 2) As String
seats(0, 0) = "Ines" : seats(1, 2) = "Tomás"
Console.WriteLine($"rows {seats.GetLength(0)}, seats per row {seats.GetLength(1)}, back corner: {seats(1, 2)}")
End Sub
End ModuleIt prints:
4 waiting: Yusuf, Amara, Chiara, Dmitri; first is Yusuf
no lentils in stock
rice 17
beans 12
salt 5
[repeat: the] [repeat: and] [repeat: the] [repeat: river]
5 distinct words
5 slots: 1.5 2.5 3.5 4.5 0
rows 2, seats per row 3, back corner: TomásList(Of T)grows as needed.From {...}is a collection initializer (Visual Basic 10), which callsAddfor each item. Items are read with parentheses,queue(0), like array elements.Dictionary(Of TKey, TValue)maps keys to values using a hash table, so a lookup takes about the same time whatever its size. Its initializer takes pairs in nested braces. Assigningstock("salt") = 5adds or replaces; reading a missing key throws, so useTryGetValue(whose second argument is passedByRefand receives the value) orContainsKey. Iterating gives entries with.Keyand.Value.HashSet(Of T)keeps each value once. ItsAddreturnsFalseif the value was already present, which turns "have I seen this before?" into one line.ReDim Preserveresizes an array, copying the old contents; new slots get the default value, which is why the fifth reading is 0. It is common in code that predatesList(Of T). EachReDim Preservecopies the whole array, so growing an array one element at a time in a loop is slow; replacing such arrays with aList(Of T)is a standard modernisation.- Multi-dimensional arrays, such as
seats(1, 2)(two rows of three seats, remembering upper bounds), are still useful for grids.GetLength(0)andGetLength(1)give the sizes of each dimension. - A colon
:separates several statements on one line. It is legal and occasionally convenient, but most style guides discourage it.
Which collection should you choose?
| You need | Use | Cost of a lookup |
|---|---|---|
| an ordered, growable list, accessed by position | List(Of T) | by position: constant; by value: proportional to the length |
| to find values by a key | Dictionary(Of TKey, TValue) | about constant on average |
| to know whether you have seen a value | HashSet(Of T) | about constant on average |
| keys kept in sorted order | SortedDictionary(Of TKey, TValue) | grows with the logarithm of the size |
| first in, first out / last in, first out | Queue(Of T) / Stack(Of T) | constant at the ends |
Queue(Of T), Stack(Of T), SortedDictionary(Of TKey, TValue) and the rest of the .NET collections work the same way. The old Collection class from classic Visual Basic (one-based, holding Object) still exists in Microsoft.VisualBasic for compatibility; prefer the generic collections in new code.
LINQ in Visual Basic
Definition— LINQ query
An expression that describes a computation over a sequence: filtering (Where), ordering (Order By), projecting (Select), grouping (Group By), joining (Join) and aggregating (Aggregate). Visual Basic offers it in two forms: query syntax, which reads like a sentence, and method syntax, a chain of method calls with lambdas. The compiler translates query syntax into the method calls.
Here are a season's harvests from cooperatives in three regions of Ghana (made-up figures), queried several ways:
Option Strict On
Public Class Harvest
Public Property Region As String
Public Property Crop As String
Public Property Tonnes As Double
End Class
Module Program
Sub Main()
Dim harvests As New List(Of Harvest) From {
New Harvest With {.Region = "Ashanti", .Crop = "cocoa", .Tonnes = 41.5},
New Harvest With {.Region = "Ashanti", .Crop = "maize", .Tonnes = 18},
New Harvest With {.Region = "Volta", .Crop = "maize", .Tonnes = 26},
New Harvest With {.Region = "Volta", .Crop = "rice", .Tonnes = 12.5},
New Harvest With {.Region = "Bono", .Crop = "cocoa", .Tonnes = 33},
New Harvest With {.Region = "Bono", .Crop = "maize", .Tonnes = 9.5}
}
' Query syntax: From, Where, Order By, Select.
Dim maize = From h In harvests
Where h.Crop = "maize"
Order By h.Tonnes Descending
Select h.Region, h.Tonnes
For Each m In maize
Console.WriteLine($"maize {m.Region,-8} {m.Tonnes,5}")
Next
' Group By ... Into: totals per crop, with an anonymous type for each result.
Dim byCrop = From h In harvests
Group By h.Crop Into Total = Sum(h.Tonnes), Regions = Count()
Order By Total Descending
For Each g In byCrop
Console.WriteLine($"{g.Crop,-6} {g.Total,6} t, {g.Regions} region(s)")
Next
' Aggregate ... Into computes a single value (a Visual Basic query keyword).
Dim grandTotal = Aggregate h In harvests Into Sum(h.Tonnes)
Dim biggest = Aggregate h In harvests Into Max(h.Tonnes)
Console.WriteLine($"total {grandTotal} t, largest single harvest {biggest} t")
' The same kind of query in method syntax, with Function lambdas.
Dim regionNames = harvests.Select(Function(h) h.Region).Distinct().OrderBy(Function(r) r)
Console.WriteLine(String.Join(", ", regionNames))
' Anonymous types with New With; Key fields take part in equality.
Dim a = New With {Key .Crop = "cocoa", .Tonnes = 1.0}
Dim b = New With {Key .Crop = "cocoa", .Tonnes = 2.0}
Console.WriteLine($"equal by key? {a.Equals(b)}")
End Sub
End ModuleIt prints:
maize Volta 26
maize Ashanti 18
maize Bono 9.5
cocoa 74.5 t, 2 region(s)
maize 53.5 t, 3 region(s)
rice 12.5 t, 1 region(s)
total 140.5 t, largest single harvest 41.5 t
Ashanti, Bono, Volta
equal by key? TrueFrom h In harvestsintroduces a range variable,h, which stands for each element in turn.Where,Order By ... DescendingandSelectread in the order the data flows, and you can write them in different orders and repeat them.Select h.Region, h.Tonnescreates an anonymous type with two properties, used directly in the loop.Group By h.Crop Into Total = Sum(h.Tonnes), Regions = Count()groups by crop and computes aggregates for each group in one clause, a form only Visual Basic has. The result has propertiesCrop,TotalandRegions.Aggregate ... Intocomputes a single value from a sequence: a sum, a maximum, an average, a count. In C# you would callSum()andMax()methods instead.- Method syntax chains
Select,DistinctandOrderBy, each taking aFunctionlambda. Both forms produce the same kind of query; use whichever reads better. - Anonymous types are created with
New With {...}. Properties markedKeytake part in equality and are read-only, soaandbare equal because theirCropkeys match.
A side note on names: the query declares a range variable Regions, so the program could not also have a local variable called regions in the same procedure; because Visual Basic ignores case, they would be the same name. The compiler reports the clash (error BC30978), which is why the later list is called regionNames.
Joins and more query keywords
Queries can combine collections. This one matches students to their marks, computes a grade for each mark, and shows a few more of Visual Basic's query keywords:
Option Strict On
Public Class Student
Public Property Id As Integer
Public Property Name As String
End Class
Public Class Mark
Public Property StudentId As Integer
Public Property Subject As String
Public Property Score As Integer
End Class
Module Program
Sub Main()
Dim students As New List(Of Student) From {
New Student With {.Id = 1, .Name = "Aiko"},
New Student With {.Id = 2, .Name = "Bongani"},
New Student With {.Id = 3, .Name = "Carmen"}
}
Dim marks As New List(Of Mark) From {
New Mark With {.StudentId = 1, .Subject = "Maths", .Score = 88},
New Mark With {.StudentId = 2, .Subject = "Maths", .Score = 71},
New Mark With {.StudentId = 1, .Subject = "Art", .Score = 95},
New Mark With {.StudentId = 3, .Subject = "Maths", .Score = 64},
New Mark With {.StudentId = 2, .Subject = "Art", .Score = 80}
}
' Join matches items from two collections; Let names an intermediate value.
Dim report = From s In students
Join m In marks On s.Id Equals m.StudentId
Let grade = If(m.Score >= 85, "A", If(m.Score >= 70, "B", "C"))
Order By s.Name, m.Subject
Select s.Name, m.Subject, m.Score, grade
For Each r In report
Console.WriteLine($"{r.Name,-8} {r.Subject,-6} {r.Score,3} {r.grade}")
Next
' Skip, Take and Distinct are query keywords in Visual Basic.
Dim secondAndThird = From m In marks Order By m.Score Descending Skip 1 Take 2 Select m.Score
Console.WriteLine($"2nd and 3rd best: {String.Join(", ", secondAndThird)}")
Dim subjects = From m In marks Select m.Subject Distinct
Console.WriteLine($"subjects: {String.Join(", ", subjects)}")
' Group Join: each student with all of their marks, even if there are none.
Dim averages = From s In students
Group Join m In marks On s.Id Equals m.StudentId Into Average(m.Score)
Select s.Name, Average
For Each a In averages
Console.WriteLine($"{a.Name}: {a.Average:F1}")
Next
End Sub
End ModuleIt prints:
Aiko Art 95 A
Aiko Maths 88 A
Bongani Art 80 B
Bongani Maths 71 B
Carmen Maths 64 C
2nd and 3rd best: 88, 80
subjects: Maths, Art
Aiko: 91.5
Bongani: 75.5
Carmen: 64.0Join ... On ... Equalspairs each student with each of their marks, like an inner join in SQL. The keyword isEquals, not=, because the two sides belong to different collections.Letnames a value computed inside the query, here a grade, which later clauses can use. The nestedIf()chooses among three grades.Order By s.Name, m.Subjectsorts by name, then by subject within each name.Skip,TakeandDistinctare query clauses in Visual Basic; C# offers them only as methods. Paging through results ("skip the first 20, take the next 10") is the classic use ofSkipandTake.Group Join ... Into Average(m.Score)gives each student the average of their marks, computed in the same clause. UnlikeJoin, a group join keeps students who have no marks at all (their group is simply empty).
Queries run when you use them
A query is a recipe, not a result. It runs each time it is enumerated, by a For Each or by methods such as Count(), ToList() or First(), and it sees the collection as it is then. Exercise 4 shows this: add an item after writing the query, and the query includes it. Call ToList() to take a snapshot when you need one, and avoid enumerating an expensive query (one that reads a database, for example) several times.
XML literals
XML is everywhere in older business systems: configuration files, data exchange with suppliers and banks, reports, office documents. Visual Basic 9 (2008) made XML part of the language. You can write an XML element directly in code, insert values with embedded expressions written as <%= ... %>, and read XML with axis properties: .<child> for child elements, ...<name> for descendants at any depth, and .@name for an attribute.
Option Strict On
Module Program
Sub Main()
Dim books = {
New With {.Title = "Things Fall Apart", .Author = "Chinua Achebe", .Year = 1958},
New With {.Title = "Pedro Páramo", .Author = "Juan Rulfo", .Year = 1955},
New With {.Title = "The Tale of Genji", .Author = "Murasaki Shikibu", .Year = 1010}
}
' XML literals: XML written directly in the code, with <%= %> holes for values.
Dim catalogue =
<catalogue updated=<%= "2026-11-19" %>>
<%= From b In books
Order By b.Year
Select <book year=<%= b.Year %>>
<title><%= b.Title %></title>
<author><%= b.Author %></author>
</book> %>
</catalogue>
Console.WriteLine(catalogue)
' Axis properties query XML: .<child>, ...<descendant>, .@attribute
Dim modern = From book In catalogue.<book>
Where CInt(book.@year) > 1900
Select book.<title>.Value
Console.WriteLine("Modern: " & String.Join("; ", modern))
Console.WriteLine($"Updated {catalogue.@updated}, {catalogue...<author>.Count()} authors")
End Sub
End ModuleIt prints:
<catalogue updated="2026-11-19">
<book year="1010">
<title>The Tale of Genji</title>
<author>Murasaki Shikibu</author>
</book>
<book year="1955">
<title>Pedro Páramo</title>
<author>Juan Rulfo</author>
</book>
<book year="1958">
<title>Things Fall Apart</title>
<author>Chinua Achebe</author>
</book>
</catalogue>
Modern: Pedro Páramo; Things Fall Apart
Updated 2026-11-19, 3 authorscatalogue is an XElement (from System.Xml.Linq, imported automatically in Visual Basic projects). The embedded expression inside it is itself a LINQ query whose Select produces more XML literals, one book element per item, ordered by year. Values are escaped correctly, so a title containing & or < cannot break the XML. Printing the element formats it with indentation.
The query at the end reads the XML back: catalogue.<book> is the sequence of book children, book.@year the text of an attribute (converted with CInt), and book.<title>.Value the text of the first title child. catalogue...<author> finds author elements at any depth. (The year given for The Tale of Genji, written in the early eleventh century, is approximate.)
C# programmers do the same work with XElement constructors and methods, which is perfectly workable but much more verbose. In Visual Basic codebases, XML literals are often the most elegant code in the project; when such code is migrated to C#, this is one of the parts that grows the most.
Modernising collection code
Typical improvements a maintainer makes to older Visual Basic collection code, each small and testable on its own:
- Replace arrays that grow with
ReDim PreservebyList(Of T); replace the untypedCollectionandArrayListwith generic collections, which remove casts and catch type errors at compile time. - Replace nested loops that search, filter and total by a LINQ query that states the question. Keep the loop where it is clearer, for example when it has several side effects.
- Replace hand-built XML strings (
"<book>" & title & "</book>", which breaks on a title containing&) with XML literals orXElement. - Use
Dictionarylook-ups instead of searching a list in a loop. For large inputs this turns quadratic work into linear work, often the biggest single speed-up available in old code. - With
Option Strict On, collection code that relied on late binding (anArrayListof objects whose members were called directly) will stop compiling. The errors show exactly where types need to be stated.
From Collection to LINQ
Classic Visual Basic programmers had arrays, whose lower bound could even be changed to 1 with Option Base 1 (so code was full of LBound and UBound), and the Collection object, a one-based list of untyped items with optional string keys. Many projects also used the Scripting.Dictionary object from the Windows scripting runtime. Each lookup returned a Variant, the catch-all type of the time, and mistakes in types showed up only when the program ran.
Visual Basic .NET brought typed .NET collections, and generics (2005) made them safe: a List(Of Integer) holds only integers. LINQ arrived with Visual Basic 9 (Visual Basic 2008) and .NET 3.5 at the end of 2007, together with lambdas, anonymous types, type inference and XML literals, all designed together so that queries could be written naturally. That release is the reason so much "modern-looking" Visual Basic dates from around 2008 to 2015.
Common misconceptions
Misconception
"A query is a list of results." It is a description of how to compute them, evaluated each time it is enumerated. Call ToList() or ToArray() when you want the results fixed.
Misconception
"LINQ is only for databases." LINQ to Objects, over in-memory collections, is the most common use. The same syntax also queries XML (LINQ to XML) and, through Entity Framework, databases.
Misconception
"XML literals make code depend on a special XML library." They compile to ordinary XElement and XAttribute objects from System.Xml.Linq, part of .NET. C# code can use the XML that Visual Basic creates, and the other way round.
Exercises
1. Collections, LINQ and XML
Warm-upComputationalWhat does this code print?
Dim items As New List(Of Integer) From {4, 8, 15}
items.Add(16)
items.Insert(1, 23)
items.Remove(8)
Console.WriteLine(String.Join(",", items))
2. Collections, LINQ and XML
Warm-upComputationalWhat does this code print?
Dim q = From n In {5, 3, 8, 1} Where n > 2 Order By n Select n * 10
Console.WriteLine(String.Join(" ", q))
3. Collections, LINQ and XML
CoreComputationalWhat does this code print?
Dim words = {"sun", "rain", "wind", "fog", "storm"}
Dim longOnes = Aggregate w In words Where w.Length > 3 Into Count()
Console.WriteLine(longOnes)
4. Collections, LINQ and XML
CoreComputationalWhat does this program print?
Option Strict On
Module Program
Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3}
Dim bigOnes = From n In numbers Where n > 1 Select n
numbers.Add(10)
Console.WriteLine(bigOnes.Count())
End Sub
End Module
5. Collections, LINQ and XML
CoreComputationalWhat does this program print?
Option Strict On
Module Program
Sub Main()
Dim order = <order id="A17"><line qty="2">tea</line><line qty="5">sugar</line></order>
Dim total = Aggregate l In order.<line> Into Sum(CInt(l.@qty))
Console.WriteLine($"{order.@id} {total}")
End Sub
End Module
6. Collections, LINQ and XML
CoreHumanAn old import routine checks, for each of 200,000 incoming customer codes, whether the code is already in a List(Of String) of known codes, using knownCodes.Contains(code). It has become very slow. What is the best fix?
Further reading and resources
- Collections (Visual Basic) · MicrosoftChoosing and using collection classes.
- Introduction to LINQ in Visual Basic · MicrosoftQuery syntax, including the clauses only Visual Basic has.
- XML literals overview · MicrosoftXML literals, embedded expressions and axis properties.