0

I would like to build an array whose rows are keyed with a string. The rows need not have the same number of columns (jagged array) or have values in each column. I want to be able to update columns in an existing row of the array.

I tried using a Dictionary.

Dim ToolUsers as New Dictionary(Of String, Array)
Dim UserData() As String = {"", "", "", "", "", "", "", "")

The Of String lets me access any particular row based on the String value but Array is a reference type and always points to the current values stored in the UserData array instead of being a value type and storing the array values in the Dictionary.

I looked at an Array of Arrays but it does not appear to allow access to existing rows via a key or allow updating the existing values.

Does such a construct exist in VB.net?

Mark
  • 8,140
  • 1
  • 14
  • 29
  • The Dictionary should work. You need to create a new array for each new Dictionary item, you can't just modify the values of an existing array and expect to create a new Dictionary item with different data. – Blackwood Feb 05 '15 at 22:31
  • Hard to see why value type behavior is important to you. Maybe you are overlooking Array.Copy(). – Hans Passant Feb 05 '15 at 23:27

1 Answers1

0

You can achieve what you want using a Dictionary, but arrays in .NET are reference types, so you need to be careful how you populate your dictionary, and not reuse the same array if you really want different data in each item. e.g.

' Create a dictionary from string to array of string
Dim x = New Dictionary(Of String, String())()
x("A") = New String() { "A1", "A2", "A3" }
' A : A1, A2, A3
x("A")(1) = "A2x"
' A : A1, A2x, A3
Dim y = New String() { "Y1", "Y2" }
x("Y1") = y ' points to same array as y
x("Y2") = DirectCast(y.Clone(), String()) ' shallow copy of y, which is OK since String is immutable
' A : A1, A2x, A3
' Y1 : Y1, Y2
' Y2 : Y1, Y2
y(0) = "Y1x"
' A : A1, A2x, A3
' Y1 : Y1x, Y2
' Y2 : Y1, Y2
Community
  • 1
  • 1
Mark
  • 8,140
  • 1
  • 14
  • 29