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

你说的曾经没有我的故事 提交于 2019-12-22 02:34:06

问题


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


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2628223/adding-items-to-the-list-at-creation-time-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!