tmighty
tmighty

Reputation: 11399

Convenient way to add a structure to a list of structures

I have defined a structure like this:

Private Structure udtString2
    Dim String1 As String
    Dim String2 As String
End Structure

Now I want to fill a list of udtString2 with values, and I would like to do it in a convinient, well structured and easy to read way.

I would like to ask if it is possible to do something like this?

Dim n As New List(Of udtString2)

'Pseudocode

n.Add(udtString2("TextA1", "TextA2"))
n.Add(udtString2("TextB1", "TextB2"))

Or if there's any other to do it as nicely visible like this.

Upvotes: 0

Views: 1827

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56433

you could try this:

n.Add(New udtString2() With { .String1 = "TextA1", .String2 = "TextB1" })
...
...
...

Also, you could use a collection initializer to make it more compact rather than calling n.Add subsequently.

Upvotes: 1

John Koerner
John Koerner

Reputation: 38077

Define a constructor for your structure:

Private Structure udtString2
    Dim String1 As String
    Dim String2 As String

    Public Sub New (s1 as String, s2 As String)
        String1 = s1
        String2 = s2
    End Sub
End Structure

Then you can use it almost how you want:

n.Add(new udtString2("TextA1", "TextA2"))
n.Add(new udtString2("TextB1", "TextB2"))

Upvotes: 3

Related Questions