Search code examples
.netinitializer

List(of myclass) initializer vb.net


I have a class like this

Class Myclass
  itemdata as string
  name as string
End Class

how do i initialised this class with and array of string for both properties?

this is what i am trying, which os obviously wrong

Dim ls As New List(Of Myclass)(New Myclass() {("A1,A2,A3,A4".Split(","))})

I need something like this after initialization, the value of each item in the list will be like as if assigned manually like this

List(0).itemdata="A1"
List(0).name="A1"
List(1).itemdata="A2"
List(2).name="A2"

etc


Solution

  • To start with Myclass is a reserved name, so I've used Myclass2.

    This is the closest to you code that I can make it:

    Dim dicOpts = New Dictionary(Of String, String) From {{"foo", "bar,woo"}}
    Dim key = "foo"
    Dim ls As New List(Of Myclass2) From { New Myclass2() With { .itemdata = dicOpts(key).Split(","c)(0), .name = dicOpts(key).Split(","c)(1) } }
    

    That gives:

    result


    Based on your edits I think this is closer to what you want:

    Dim text = "A1,A2,A3,A4"
    Dim ls = _
        text _
            .Split(","c) _
            .Select(Function (x) New Myclass2() With { .itemdata = x, .name = x }) _
            .ToList()
    

    I now get this:

    result2