65.9K
CodeProject is changing. Read more.
Home

How to dynamically retrieve results from a LINQ Query

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Dec 3, 2010

CPOL
viewsIcon

14544

Iterate through the results and extract using system.reflection

I looked for days for an answer and couldn't find one. Here's my solution on how to dynamically retrieve the results from a LINQ Query. If you're stuck, I hope this helps. -james
'The following code will dynamically extract the
'field name and value from a LINQ IQueryable result.
'
'You need to:
'     Add Imports System.Reflection to your class
'     Create a LinqQuery and data context (if you're
'     looking at this code, I'm sure you know how.)
'
'Iterate through the result rows
For Each CurrentRow In LinqQuery

  'For each field in a row get property information
  'from the class
  For Each FieldPropertyInfo In CurrentRow.GetType.GetProperties

    'Retreive method you would call in code to get the
    'value of the field
    Dim GetMeth As System.Reflection.MethodInfo =
                   FieldPropertyInfo.GetGetMethod()

    'Invoke the method on the CurrentRow and retretrieve
    'the value
    Dim value As Object = GetMeth.Invoke(CurrentRow, Nothing)

    'Take a peek at the results
    Debug.Print(FieldPropertyInfo.Name & ": " & value.ToString)

  Next

Next