[ACCEPTED]-Creating a list of Anonymous Type in VB-anonymous-types

Accepted answer
Score: 15

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

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

Now you can just do the following

Dim list = CreateListFromSingle(dsResource)

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

There are 2 ways to do this. You 4 can use the following code to create an 3 empty list. It borders on hacky because 2 you are passing parameters you don't ever 1 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 })
Score: 12

Here is how to do it inline using casting 5 by example (without creating a second function):

Sub Main()
    Dim x = New With {.Name = "Bob", .Number = 8675309}
    Dim xList = {x}.ToList()
End Sub

(based 4 on c# version posted here )

Essentially you create 3 the anonymous type, put it in an array ( {x} ) then 2 use the array's .ToList() method to get 1 a list.

Score: 9

How about a single line construct like this?

Dim yourList = {(New With {.Name="", .Age=0})}.Take(0).ToList


Score: 6

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

The best way 3 is to introduce a generic function that 2 creates an empty collection from a prototype 1 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
Score: 2

I like Jared's solution but just to show 5 the direct equivalent of Jon's code (notwithstanding 4 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 3 it's not extensible … but may be used to 2 seed other LINQ magic for creating larger 1 lists.

Score: 2

In a single line you can add anonymous types 1 into a list

Dim aList = {(New With {.Name="John", .Age=30}), (New With {.Name="Julie", .Age=32})}.ToList
Score: 0

If you're adding values to the list by iteration, I 2 assume you have an IEnumerable to start with? Just 1 use .Select with .ToList. That's what it's designed for.

Dim l = dsResources.Select(Function(d) New With {
                              .Name = d.Last_Name & ", " & d.First_Name

More Related questions