Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a VB.NET Array with two columns of values?

I know how to create an array and loop through it normally - but what if I need a multi-column array. e.g. usually I might do something like:

For Each row in NameofArray
  Dim name as String = row
  Response.Write("Hello " & name & "!")
Next

But what if I want to do something like:

For Each row in NameofArray
   Dim name as String = row.name
   Dim age as Integer = row.age
   Response.Write("Hello " & name & "! You are " & age & " years old!"
Next

If this isn't possible with an array, is there another way I can accomplish this?

like image 400
Dave Mackey Avatar asked Dec 28 '22 22:12

Dave Mackey


2 Answers

Create your custom data type:

 public struct DataType 
    public string Name; 
    public int Age; 
 }

Such type you can than use in an array like that:

 DataType[] myData = new DataType[100]; 
 myData[0].Name = "myName"; 
 myData[0].Age = 100; 

Note, if looping through that array via foreach, the elements returned for each iteration cannot get altered. If this is an requirement for you, consider using 'class' rather than 'struct' in the above DataType declaration. This will come with some other implications though. For example, the instances of a class DataType will explicitely have to be created via the 'new' keyword.

like image 192
user492238 Avatar answered Jan 10 '23 11:01

user492238


After reading your comment I think my other answer is probably what you are looking for.

What type is row and what type is NameOfArray?

If you would like to make row into a coumpound type with several members then there a several options.

Structure Row
   Public Name as String
   Public Age as Integer
End Structure

for instance. If you would prefer a reference type substitute Class for Structure.

Or using anonymous types,

Dim row = New With {Name = "Bob", Age = 21}

Then you can use generics to make a list of rows that you can iterate through using ForEach.

Dim NameOfList As System.Collections.Generic.List(of Row)

or if it were a result of a LINQ query somthing that supported

IEnumerable(of New With{Name As String, Age As Int}). //Not sure if this is VB

I'm not certain I uderstand your question and hope this is the kind of thing you were looking for.

As you can see from my fellow answerers, the support for anonymous types is superior in C# but, since you asked the question in VB.Net I will limit myself to that context.

like image 34
Jodrell Avatar answered Jan 10 '23 12:01

Jodrell