Adding items to the List at creation time in VB.Ne

2019-04-19 12:12发布

In c# I can initialize a List at creation time like

var list = new List<String>() {"string1", "string2"};

is there a similar thing in VB.Net? Currently I can do it like

Dim list As New List(Of String)
list.Add("string1")
list.Add("string2")
list.Add("string3")

but I want to avoid boring .Add lines

3条回答
放我归山
2楼-- · 2019-04-19 12:58

VB10 supports collection initializers. I believe your example would be:

Dim list As New List(Of String) From { "string1", "string2", "string3" }

MSDN has more information.

查看更多
Animai°情兽
3楼-- · 2019-04-19 13:02
Dim a As New List(Of String)(New String() {"str1", "str2"})

Though if it's VB 2010 I'd definitely go with Jon Skeet's answer.

查看更多
【Aperson】
4楼-- · 2019-04-19 13:11

You can also use AddRange if you don't want to put all of your items on a single line.

Dim list As New List(Of String) From { "string1", "string2", "string3" }
list.addRange({"string4", "string5", "string6"})
查看更多
登录 后发表回答