LINQ OrderBy排序问题

时间:2011-03-31 16:17:23

标签: vb.net 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

但那没用。

2 个答案:

答案 0 :(得分:1)

您应该在Linq中查看称为动态查询的内容。

Using the LINQ Dynamic Query Library

答案 1 :(得分: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