Creating Arrays
Store and manage collections of data efficiently in Visual Basic 2026 — declare one-dimensional and two-dimensional arrays, iterate with For/For Each loops, use Array methods to sort and search, work with dynamic arrays and List(Of T), and harness LINQ for powerful data queries, with GitHub Copilot assistance throughout.
name1, name2, name3… you declare one array names(99) and use a loop to process all 100 values with just a few lines of code. In VB 2026 / .NET 10, arrays are complemented by the more flexible List(Of T) collection and powerful LINQ queries that let you filter, sort, and transform array data in a single expressive line.
10.1 Why Use Arrays?
Consider storing the marks of 5 students. Without an array you need five separate variables:
' Without array — tedious, error-prone, doesn't scale Dim mark1 As Integer = 78 Dim mark2 As Integer = 92 Dim mark3 As Integer = 65 Dim mark4 As Integer = 88 Dim mark5 As Integer = 71 ' Imagine 100 students — 100 Dim statements!
' With array — one name, many values, works for any size Dim marks() As Integer = {78, 92, 65, 88, 71} ' Access by zero-based index lblFirst.Text = marks(0).ToString() ' 78 — index starts at 0 lblLast.Text = marks(4).ToString() ' 71 ' Process all values with a loop — scales to any size Dim total As Integer = 0 For i = 0 To marks.Length - 1 total += marks(i) Next lblAvg.Text = $"Average: {total / marks.Length:F1}"
10.2 One-Dimensional Arrays
Declaration Syntax
VB 2026 provides three ways to declare a one-dimensional array. The index in the declaration specifies the upper bound (last valid index), not the number of elements.
' ── Method 1: Declare with upper bound (5 elements: 0..4) ── Dim scores(4) As Integer ' indexes 0,1,2,3,4 — all default to 0 Dim names(9) As String ' 10 strings, all Nothing Dim prices(99) As Decimal ' 100 Decimal values ' ── Method 2: Declare and initialise with literal values ─── Dim days() As String = {"Mon", "Tue", "Wed", "Thu", "Fri"} Dim primes() As Integer = {2, 3, 5, 7, 11, 13, 17} ' ── Method 3: Type inference from initialiser ───────────── Dim colours = {"Red", "Green", "Blue"} ' String() inferred Dim temps = {36.5, 37.1, 36.8} ' Double() inferred ' Key array properties Dim size = scores.Length ' 5 — total number of elements Dim lastIdx = scores.Length - 1 ' 4 — last valid index (always Length-1) Dim upper = scores.GetUpperBound(0) ' 4 — same as Length-1 for 1D ' Reading and writing elements scores(0) = 85 ' assign to index 0 scores(4) = 72 ' assign to index 4 (last) Dim first = scores(0) ' read index 0
VB 2026 arrays always start at index 0. Dim marks(4) As Integer creates 5 elements: marks(0) through marks(4). The number in the brackets is the upper bound (highest valid index), not the count. This differs from VB 6 where you could set Option Base 1 to start at 1. In VB 2026, Option Base is not supported — always 0.
Iterating Arrays
Dim fruits() As String = {"Apple", "Banana", "Cherry", "Durian", "Elderberry"} ' ── For loop — use when you need the index ───────────── For i = 0 To fruits.Length - 1 lstFruits.Items.Add($"[{i}] {fruits(i)}") Next ' ── For Each — cleaner when you don't need the index ─── For Each fruit As String In fruits lstFruits.Items.Add(fruit) Next ' ── Calculate sum and average ────────────────────────── Dim scores() As Integer = {88, 72, 95, 61, 84} Dim total As Integer = 0 Dim highest As Integer = scores(0) Dim lowest As Integer = scores(0) For Each s As Integer In scores total += s If s > highest Then highest = s If s < lowest Then lowest = s Next Dim average = total / scores.Length lblStats.Text = $"Total:{total} Avg:{average:F1} High:{highest} Low:{lowest}"
Enter up to 8 integer scores separated by commas, then use the buttons to get, set, sort, and calculate statistics.
10.3 Two-Dimensional Arrays
A two-dimensional array is a table of values with rows and columns. You access elements with two indexes: array(row, column). It is perfect for storing a grid of data such as a class mark sheet, game board, or multiplication table.
' ── Declare a 3×4 array (3 rows, 4 columns) ─────────────── Dim marks(2, 3) As Integer ' rows 0..2, columns 0..3 ' ── Assign values ───────────────────────────────────────── marks(0, 0) = 85 : marks(0, 1) = 90 : marks(0, 2) = 78 : marks(0, 3) = 92 marks(1, 0) = 70 : marks(1, 1) = 65 : marks(1, 2) = 88 : marks(1, 3) = 74 marks(2, 0) = 95 : marks(2, 1) = 82 : marks(2, 2) = 76 : marks(2, 3) = 89 ' ── Initialise with literal values ────────────────────── Dim grid(,) As Integer = {{85,90,78,92}, {70,65,88,74}, {95,82,76,89}} ' ── Nested loops to process all cells ─────────────────── Dim rows = grid.GetLength(0) ' 3 rows Dim cols = grid.GetLength(1) ' 4 columns For r = 0 To rows - 1 Dim rowTotal As Integer = 0 For c = 0 To cols - 1 rowTotal += grid(r, c) Next Dim avg = rowTotal / cols lstResults.Items.Add($"Student {r + 1}: Total={rowTotal} Avg={avg:F1}") Next
A 3-student × 4-subject marks grid. Click any cell to highlight it, or click Calculate to see row totals and averages.
| row\col | [,0] Maths | [,1] Science | [,2] English | [,3] History |
|---|
10.4 Array Methods — Sort, Search, Copy
The Array class in .NET provides a rich set of static methods for manipulating arrays without writing manual loops:
Dim nums() As Integer = {42, 7, 98, 15, 63, 28} ' ── Sort ascending ────────────────────────────────────── Array.Sort(nums) ' nums is now: {7, 15, 28, 42, 63, 98} ' ── Reverse (descending after sort) ───────────────────── Array.Reverse(nums) ' nums is now: {98, 63, 42, 28, 15, 7} ' ── Linear search ─────────────────────────────────────── Dim idx = Array.IndexOf(nums, 42) ' returns 2 (position of 42) If idx >= 0 Then lblFind.Text = $"Found 42 at index {idx}" Else lblFind.Text = "Not found" End If ' ── Binary search (array must be sorted first) ────────── Array.Sort(nums) Dim pos = Array.BinarySearch(nums, 42) ' much faster for large arrays ' ── Resize — change number of elements ────────────────── Array.Resize(nums, 10) ' grows to 10; new elements = 0 Array.Resize(nums, 3) ' shrinks to 3; excess discarded ' ── Copy ──────────────────────────────────────────────── Dim backup(5) As Integer Array.Copy(nums, backup, nums.Length) ' full copy ' ── Fill (new in .NET 10) ─────────────────────────────── Dim zeros(9) As Integer Array.Fill(zeros, -1) ' fill all 10 elements with -1
10.5 Dynamic Arrays with ReDim
Sometimes you don't know the required array size at compile time. VB 2026 supports dynamic arrays — declared without a size and resized at runtime with ReDim. Use ReDim Preserve to keep existing values when resizing.
' Declare without size — no elements yet Dim names() As String ' ── ReDim — set or change size (discards existing data) ─ ReDim names(4) ' now has 5 elements (0..4) names(0) = "Alice" names(1) = "Bob" names(2) = "Charlie" ' ── ReDim Preserve — resize AND keep existing values ──── ReDim Preserve names(6) ' grows to 7; Alice/Bob/Charlie preserved names(3) = "Diana" names(4) = "Eve" ' ── Common pattern: grow array by 1 when user adds item ─ Private _items() As String Private _count As Integer = 0 Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click ReDim Preserve _items(_count) ' grow by one slot _items(_count) = txtItem.Text.Trim() ' store in new slot _count += 1 lstItems.Items.Add(_items(_count - 1)) txtItem.Clear() End Sub
Calling ReDim Preserve repeatedly is slow — it allocates a new array and copies every element each time. For collections that grow and shrink frequently, use List(Of T) instead (covered next). ReDim Preserve is fine for occasional resizes or when you need a true array type for interoperability with APIs that require arrays.
10.6 List(Of T) — The Modern Alternative
List(Of T) is a dynamic collection that grows and shrinks automatically — no ReDim needed. It provides all the array-like features you need plus convenient Add, Remove, Contains, and Sort methods. In VB 2026 it is the preferred choice whenever the collection size is not fixed.
' ── Create a List(Of T) ───────────────────────────────── Dim students As New List(Of String)() Dim scores As New List(Of Integer)() ' ── Add items ─────────────────────────────────────────── students.Add("Alice") students.Add("Bob") students.Add("Charlie") students.AddRange({"Diana", "Eve"}) ' ── Access by index (same as arrays) ─────────────────── Dim first = students(0) ' "Alice" Dim count = students.Count ' 5 ' ── Remove items ──────────────────────────────────────── students.Remove("Bob") ' remove by value students.RemoveAt(0) ' remove by index ' ── Search ────────────────────────────────────────────── Dim exists = students.Contains("Charlie") ' True Dim idx = students.IndexOf("Diana") ' returns index ' ── Sort and iterate ──────────────────────────────────── students.Sort() For Each name As String In students lstNames.Items.Add(name) Next ' ── Convert between array and List ───────────────────── Dim arr() = students.ToArray() ' List → array Dim backToList = New List(Of String)(arr) ' array → List
Add, remove, search, and sort a List(Of String) — demonstrating dynamic resizing without ReDim.
10.7 New in VB 2026 / .NET 10 — LINQ Array Queries
LINQ (Language Integrated Query) lets you filter, sort, group, and aggregate arrays and collections using expressive query syntax. Import System.Linq and use methods like Where(), OrderBy(), Select(), Max(), Average(), and Count() directly on any array.
Imports System.Linq Dim scores() As Integer = {88, 72, 95, 61, 84, 55, 91, 67} ' ── Aggregate queries ─────────────────────────────────── Dim highest = scores.Max() ' 95 Dim lowest = scores.Min() ' 55 Dim average = scores.Average() ' 76.625 Dim total = scores.Sum() ' 613 ' ── Filter with Where ─────────────────────────────────── Dim passed = scores.Where(Function(s) s >= 50).ToArray() ' {88, 72, 95, 61, 84, 55, 91, 67} Dim honours = scores.Where(Function(s) s >= 75).ToArray() ' {88, 95, 84, 91} ' ── Sort with OrderBy / OrderByDescending ─────────────── Dim ascending = scores.OrderBy(Function(s) s).ToArray() Dim descending = scores.OrderByDescending(Function(s) s).ToArray() ' ── Transform with Select ─────────────────────────────── Dim doubled = scores.Select(Function(s) s * 2).ToArray() Dim grades = scores.Select(Function(s) If(s >= 75, "Pass", "Fail")).ToArray() ' ── Count with condition ──────────────────────────────── Dim passCount = scores.Count(Function(s) s >= 50) ' 8 Dim failCount = scores.Count(Function(s) s < 50) ' 0 ' ── Display results ───────────────────────────────────── lblStats.Text = $"Max:{highest} Min:{lowest} Avg:{average:F1} Passed:{passCount}" lstHonours.DataSource = honours
Enter scores, pick a LINQ operation, and see results with the equivalent VB 2026 code.
10.8 GitHub Copilot — Array Assistance
' Given an Integer array of student scores, calculate and display the average, highest, lowest, pass count (>=50), and fail count in 5 Labels'' Given an Integer array of student scores, calculate and display the average, highest, lowest, pass count (>=50), and fail count in 5 Labels Imports System.Linq Dim scores() As Integer = {88, 72, 95, 61, 84, 55, 91, 67} lblAverage.Text = $"Average: {scores.Average():F1}" lblHighest.Text = $"Highest: {scores.Max()}" lblLowest.Text = $"Lowest: {scores.Min()}" lblPassCount.Text = $"Passed: {scores.Count(Function(s) s >= 50)}" lblFailCount.Text = $"Failed: {scores.Count(Function(s) s < 50)}"
' Maintain a List(Of String) of student names. Add from txtName, remove selected item from lstNames, search with txtSearch filtering the list live'' Maintain a List(Of String) of student names. Add from txtName, remove selected item from lstNames, search with txtSearch filtering the list live Private _names As New List(Of String)() Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click Dim name = txtName.Text.Trim() If String.IsNullOrEmpty(name) Then Return If Not _names.Contains(name) Then _names.Add(name) : RefreshList() End If End Sub Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click If lstNames.SelectedIndex >= 0 Then _names.Remove(lstNames.SelectedItem.ToString()) : RefreshList() End If End Sub Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged RefreshList() End Sub Private Sub RefreshList() Dim filter = txtSearch.Text.ToLower() lstNames.DataSource = _names.Where(Function(n) n.ToLower().Contains(filter)).ToList() End Sub
Try these in the Copilot Chat panel while working with arrays:
- "Find the index of the highest score in the scores array and highlight that element"
- "Remove all duplicate values from a String array using LINQ Distinct()"
- "Create a multiplication table as a 10×10 2D Integer array and display it in a DataGridView"
- "Convert a comma-separated TextBox input into a trimmed String array"
Enter student names and marks. The analyser uses arrays, sorting, and LINQ to produce a complete class report.
📘 Lesson Summary
- An array stores multiple values of the same type under one name, accessed by a zero-based index.
Dim marks(4)creates 5 elements:marks(0)tomarks(4). - Use
For i = 0 To arr.Length - 1when you need the index; useFor Each item In arrfor cleaner iteration when the index isn't needed. - 2D arrays (
Dim grid(rows-1, cols-1)) store table data. Access with two indexes:grid(row, col). Use nested For loops to process all cells. Array.Sort()sorts in-place ascending;Array.Reverse()reverses.Array.IndexOf()does linear search;Array.BinarySearch()is faster on sorted arrays.ReDim Preserveresizes a dynamic array while keeping existing values. But for collections that grow often, use List(Of T) instead — it is more efficient.- List(Of T) is the modern alternative —
Add,Remove,Contains,Sort,Count— noReDimneeded. Convert to array with.ToArray(). - In VB 2026 / .NET 10, LINQ methods (
Where,OrderBy,Select,Max,Average,Count) let you query arrays in a single expressive line without writing loops. Array.Fill(arr, value)is a new .NET 10 method that fills all elements with a value in one call.- GitHub Copilot can generate complete array-handling code — statistics, LINQ queries, dynamic list managers — from a single descriptive comment.
Exercises
Exercise 10.1 — Score Analyser
- Declare an Integer array for 10 student scores, populated from 10 TextBoxes
- Use LINQ to calculate: highest, lowest, average, total, count of passes (≥50), count of failures
- Sort the array and display the sorted scores in a ListBox
- Use
Array.IndexOf()to find and highlight the position of the highest score in the ListBox - Copilot challenge: Ask Copilot to "draw a simple bar chart of the scores on a PictureBox using GDI+"
Exercise 10.2 — Times Table Grid
- Create a 10×10 2D Integer array where
grid(i,j) = (i+1) * (j+1) - Display the multiplication table in a DataGridView with row/column headers 1–10
- When the user clicks a cell, display the equation: "3 × 7 = 21" in a Label
- Add a TrackBar to let the user highlight all multiples of a chosen number (2–12) in a different colour
- Copilot challenge: Ask Copilot to "add a quiz mode where the app asks a random multiplication question and checks the answer"
Exercise 10.3 — Dynamic To-Do List with LINQ
- Use a
List(Of String)to manage a to-do list — Add from TextBox, Remove selected, Clear all - Add a search TextBox that filters the list live using LINQ
Where()as the user types - Add Sort A→Z and Sort Z→A buttons using LINQ
OrderBy()/OrderByDescending() - Display the item count and a "No items match" message when the filter returns zero results
- Copilot challenge: Ask Copilot to "add priority tags (High/Medium/Low) to each item and sort by priority using LINQ OrderBy"
Related Resources
← Lesson 9
Variables & Constants — Dim, scope, naming, Const, ReadOnly, Enum.
Lesson 11 →
Math Operations — arithmetic operators and Math library functions.
MS Docs — Arrays
Official Microsoft reference for arrays in VB.NET including multidimensional and jagged arrays.
MS Docs — Collections
List(Of T), Dictionary, Queue, Stack and other generic collections in .NET.
Featured Books
Visual Basic 2022 Made Easy
Complete coverage of arrays, List(Of T), and LINQ with practical step-by-step projects for managing collections of data.
View on Amazon →
VB Programming With Code Examples
48 fully-explained VB.NET programs including arrays, data management, and LINQ-powered applications with full source code.
View on Amazon →