Linq returning list of anonymous types

11,537

Solution 1

The problem is that an anonymous type does not have a compile-time type that you can use as your return value for you function, so the ???? in your List(Of ????) is not something that can ever be known by the compiler.

Since you are binding this to a UI element, your best bet is probably to make the return value an IEnumerable, or IList. You should be able to bind your control to that (since binding uses reflection under the covers).

Solution 2

Anonymous types cannot leave the scope of a function. So what you are trying to do is not possible. You will have to create a type (struct or class) that you can use a return type.

Solution 3

See http://blogs.msdn.com/swiss_dpe_team/archive/2008/01/25/using-your-own-defined-type-in-a-linq-query-expression.aspx

Define your own data class object e.g. MyClass with properties ActionOn, ActionBy, Description, ImpactedItem, ActionDescription.

Then use:

Public Function GetHistory(ByVal historyId As Integer) As List(Of MyClass)
    Using dc As New myDataContext(Application.GetConnection)
        Return ( _
            From t In dc.ActionTypes, a In t.MyTable _
            Where a.HistoryID = historyId _
            Select New MyClass _
            With {.ActionOn=a.ActionOn, .ActionBy=a.ActionBy, ...} _
        ).ToList
    End Using
End Function

Solution 4

You can use te linq function CAST, then you cast your list as Object and return an Enumerable of Object.

Public Function GetHistory(ByVal historyId As Integer) As  List(Of Object)

    Using dc As New myDataContext(Application.GetConnection)

  Return (From t In dc.ActionTypes, a In t.MyTable Where _
          a.HistoryID = historyId Select a.ActionOn, a.ActionBy, _
          t.Description, a.ImpactedItem, a.ActionDescription) _
          .Cast(Of Object).ToList()

    End Using


End Function

Solution 5

If the class is the only one that'll be using the result (although this seems unlikely since you made the function Public), you can make a nested class/struct to hold the results. Otherwise, what you want to do isn't possible: Anonymous types may only have method scope.

Share:
11,537
GordonB
Author by

GordonB

Azure fanboy.

Updated on June 04, 2022

Comments

  • GordonB
    GordonB almost 2 years

    Caan somone advise the best approach to what i'm trying to acheive (linq to sql, returning list of data to show in a grid/list etc etc)... Its complaining about anonymous type conversion, and from what i'm reading, thats not elegant way of doing it.

      Public Function GetHistory(ByVal historyId As Integer) As List(Of ?????????)
        Using dc As New myDataContext(Application.GetConnection)
          Return (From t In dc.ActionTypes, a In t.MyTable Where a.HistoryID = historyId Select a.ActionOn, a.ActionBy, t.Description, a.ImpactedItem, a.ActionDescription).ToList
        End Using
      End Function