2

I have an ASP.NET page and it's associated Handler class. I would like to limit the amount of repetitious code within this handler. At the moment, I have a method that returns a DataTable containing data from two joined tables.

Public Shared Function GetAllRecords() As DataTable
        Dim dt As New DataTable

        Try
            Using context As New QREntities()
                Dim records = (From record In context.QRRecords
                          Join advert In context.QRAdvertisements On record.adId Equals advert.adId
                          Select record.recId, record.hitDate, record.hitLocation, record.ipAddress, advert.adRedirectUrl, advert.adType, advert.adData
                          Order By hitDate Descending).ToList()

                'Set the column headers and their accepted data types
                dt = SetDataTableColumns()

                For Each r In records
                    dt.Rows.Add(r.recId, r.hitDate, r.hitLocation, r.ipAddress, r.adRedirectUrl, r.adType, r.adData)
                Next
            End Using
        Catch ex As Exception
            Return Nothing
        End Try

        Return dt
    End Function

Now I would like to allow the individual to sort by any column they choose. I was considering passing a value as a parameter which is then checked in a select statement and the associated column is then used with the Order By but the issue with this is, Dim records is a List of an Anonymous Type which means I can't declare it before hand that I am aware of. My question is to everyone, what would by the best way to accomplish this?

I have looked into Query Objects, Custom Expressions and Query sets but they seem to be leading me astray.

Thanks in advance!

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
James Shaw
  • 839
  • 1
  • 6
  • 16
  • Try taking a look into the Dynamic Linq Library, I believe there is an OrderBy function that takes a string which would contain the column and directory to sort by. – James Sep 05 '12 at 19:08
  • A geeze, you are right! Wow, I feel like a goof. Thanks a lot! :) – James Shaw Sep 05 '12 at 19:30
  • And [this one](http://stackoverflow.com/a/233505/861716). – Gert Arnold Sep 05 '12 at 21:18
  • Glad it helped, went ahead and posted it as the answer that way your question doesn't get listed as unanswered. – James Sep 05 '12 at 21:44

1 Answers1

0

Dynamic Linq Library OrderBy function allows for dynamic sorting of columns and direction.

James
  • 680
  • 2
  • 8
  • 22