views:

1819

answers:

4

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
+1  A: 

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.

Jakob Christensen
+1  A: 

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).

ckramer
Returning as a generic iList did the job..... Best practice, doubtful... Workable, certainly.
GordonB
+1  A: 

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.

John Feminella
your right, thats why its public...
GordonB
A: 

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
AndrewD
FYI I've had issues with MyClass as a class ("cannot explicitly initialise class" error) - if you get the same, use a structure (you don't need a constructor - just same syntax as above)
AndrewD