tags:

views:

692

answers:

3

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

  Dim dsResource = New With {.Name = dsResourcesEnd(index).Last_Name & ", " & dsResourcesEnd(index).First_Name _
                           , .StartDate = dsResourcesStart(index).Day _
                           , .EndDate = dsResourcesEnd(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?

+4  A: 

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 })
JaredPar
Is there any way to prototype the anonymous type before assigning values to a single of that type? I'd like to have a list of that type created before I iterate through the contents I wish to add to it.
hypoxide
+3  A: 

Since the type is anonymous, you must use generic and type-inference.

The best way is to introduce a generic function that creates an empty collection from a prototype object.

Module Module1

    Sub Main()
        Dim dsResource = New With {.Name = "Foo"}

        Dim List = dsResource.CreateTypedList
    End Sub

    <System.Runtime.CompilerServices.Extension()> _
    Function CreateTypedList(Of T)(ByVal Prototype As T) As List(Of T)
        Return New List(Of T)()
    End Function

End Module
Dario
You forgot to add the the prototype element to the list … ;-)
Konrad Rudolph
I didn't ;-) This should be used to create a new list. The prototype object is just required to give information about its structure rather than about its content.
Dario
+1  A: 

I like Jared's solution but just to show the direct equivalent of Jon's code (notwithstanding my comment there):

Public Function EnumerateFromSingle(Of T)(ByVal p1 As T) As IEnumerable(Of T)
    Return New T() { p1 }
End Function

Not very useful by itself, since it's not extensible … but may be used to seed other LINQ magic for creating larger lists.

Konrad Rudolph