2012-09-05 14 views
2

我有一个ASP.NET页面并且它与Handler类相关联。我想限制这个处理程序中重复代码的数量。目前,我有一个方法返回一个包含来自两个连接表的数据的DataTable。Linq或Lambda - 允许在已连接表上定制Orderby子句的方法

 
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 

现在我想允许个人按他们选择的任何列排序。我正在考虑传递一个值作为参数,然后在select语句中检查,然后将相关列与Order By一起使用,但与此相关的问题是Dim记录是匿名类型的列表,这意味着我无法在我知道的情况下在手前宣布。我的问题是每个人,最好的办法是什么来完成这件事?

我查看了查询对象,自定义表达式和查询集,但他们似乎引导我误入歧途。

在此先感谢!

+0

试着看看动态Linq库,我相信有一个OrderBy函数需要一个字符串,它将包含要排序的列和目录。 – James

+0

哎呀,你是对的!哇,我觉得自己很愚蠢。非常感谢! :) –

+0

和[这一个](http://stackoverflow.com/a/233505/861716)。 –

回答

0

动态Linq库OrderBy函数允许动态排列列和方向。