列表(属于我的类)初始值设定项 vb.net

List(of myclass) initializer vb.net

我有一个class这样的

Class Myclass
  itemdata as string
  name as string
End Class

如何使用两个属性的字符串数组初始化此 class?

这就是我正在尝试的,os显然是错误的

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

初始化后我需要这样的东西,列表中每个项目的值就像这样手动分配一样

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

等等

我已经重命名了你的 class(es)....希望你明白你的意思:

创建您的Class:

Class xxx '(this was your 'myclass')
    Private _p1 As String
    Private _p2 As String
    Private _p3 as String

    Sub New(p1 As String, p2 As String)
        ' TODO: Complete member initialization 
        _p1 = p1
        _p2 = p2
    End Sub
    Sub New(p1 As String, p2 As String, p3 as String)
        ' TODO: Complete member initialization 
        _p1 = p1
        _p2 = p2
        _p3 = p3
    End Sub
End Class

我用 2 个重载更改了 SubNew-Method...现在你需要调用带有参数(或不带参数)的 class 的实例:

Class yyy
    Private lf As New List(Of xxx)
    Sub CallOrWhatEver()
        lf.Add(New xxx("itemdata", "name"))
        lf.Add(New xxx("p1value","p2value","p3value"))
    End Sub
End Class

Myclass开头的是保留名称,所以我使用了Myclass2

这是我能做到的最接近你的代码:

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) } }

这给出:


根据您的修改,我认为这更接近您的要求:

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

我现在明白了: