2011-03-31 182 views
0

我有一個LINQ查詢:LINQ排序依據排序問題

bikersList = (From c In ngBikersDataContext.Reg_Bikers _ 
         Order By c.L_Name _ 
         Select New Bikers() With { _ 
         .BikerID = c.BikerID, _ 
         .F_Name = c.F_Name, _ 
         .M_Name = c.M_Name, _ 
         .L_Name = c.L_Name, _ 
         .MyID = c.MyID, _ 
         .Site = c.Site.GetValueOrDefault, _ 
         .bk_Building = c.bk_Building, _ 
         .bk_City = c.bk_City, _ 
         .bk_Zip = c.bk_Zip.GetValueOrDefault, _ 
         .bk_Phone = c.bk_phone, _ 
         .email = c.email, _ 
         .DeptZone = c.DeptZone, _ 
         .QuartID = c.QuartID.GetValueOrDefault, _ 
         .BikerDays = c.BikerDays.GetValueOrDefault, _ 
         .BikerMiles = c.BikerMiles.GetValueOrDefault, _ 
         .BikerTime = c.BikerTime.GetValueOrDefault, _ 
         .BKLockID = c.BKLockID.GetValueOrDefault, _ 
         .bk_Start_DT = c.bk_Start_DT, _ 
         .bk_End_DT = c.bk_End_DT, _ 
         .bk_Quarter = c.bk_Quarter.GetValueOrDefault, _ 
         .bk_Year = c.bk_Year.GetValueOrDefault, _ 
         .bk_Comments = c.bk_Comments, _ 
         .IsActive = c.IsActive.GetValueOrDefault _ 
         }).ToList() 

這對L_Name的偉大工程和排序。但我試圖讓用戶排序gridview自己。所以我將SortExpression作爲字符串傳入。但我不知道如何將SortExpression引入到LINQ查詢中。

我試圖

Order By c. & SortExpression 

但沒有奏效。

回答

1

你應該在Linq中籤出一個名爲Dynamic Query的東西。

Using the LINQ Dynamic Query Library

+0

我想用動態庫,但我不知道如何實現它到我的項目。你可以一步一步地告訴我如何做到這一點? – 2011-03-31 19:45:43

+0

在上面的鏈接上有幾個例子。 dLINQ是否存在特定的問題,還是DLL /引用問題? – jasper 2011-04-01 00:42:59

1

下面是談論使用的SortExpression字符串使用LINQ動態排序的文章:

http://www.codeproject.com/KB/recipes/Generic_Sorting.aspx

基本上,你需要手動構建表達式樹。

(此代碼是從上面的鏈接)

Public Function Sort(ByVal source As IEnumerable(Of T), _ 
        ByVal sortBy As String, _ 
        ByVal sortDirection As String) As IEnumerable(Of T) 

    Dim param = Expression.Parameter(GetType(T), "item") 

    Dim sortExpression = Expression.Lambda(Of Func(Of T, Object))_ 
    (Expression.Convert(Expression.[Property](param, sortBy), _ 
    GetType(Object)), param) 

    Select Case sortDirection.ToLower 
     Case "asc" 
      Return source.AsQueryable().OrderBy(sortExpression) 
     Case Else 
      Return source.AsQueryable().OrderByDescending(sortExpression) 
    End Select 

End Function