Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

.net - Creating a list of Anonymous Type in VB

I'd like to create a list of an anonymous type, for example:

Dim lineItem = New With {.Name = myFile(index).Last_Name & ", " & myFile(index).First_Name, _
                         .StartDate = myFile(index).Day,
                         .EndDate = myFile(index).Day}

I have created that anonymous type. Now I'd like to add it to a list of that type. How do I declare a list of that type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a handy method for creating a list of an anonymous type from a single anonymous type.

Public Function CreateListFromSingle(Of T)(ByVal p1 As T) As List(Of T)
  Dim list As New List(Of T)
  list.Add(p1)
  return List
End Function

Now you can just do the following

Dim list = CreateListFromSingle(dsResource)

EDIT OP wanted a way to create the list before creating an element.

There are 2 ways to do this. You can use the following code to create an empty list. It borders on hacky because you are passing parameters you don't ever intend to use but it works.

  Public Function CreateEmptyList(Of T)(ByVal unused As T) As List(Of T)
    Return New List(Of T)()
  End Function

  Dim x = CreateEmptyList(New With { .Name = String.Empty, .ID = 42 })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...