当x是字符串并且我不知道T上的属性时,如何按属性x对列表(T)进行排序

时间:2013-06-06 16:08:04

标签: vb.net

我想从函数中对T列表进行排序,并按T的任何属性排序,仅按名称引用。

例如。

function sortusers(byval Users as list(of users), byval OrderBy as string, byval OrderDirection as SortDirection)

    return Sort(Of User)(Users, OrderBy, OrderDirection)

end function

return Users.Sort(OrderBy, OrderDirection)

2 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是编写扩展方法。

Module imnotgoodwithnames

''' <summary>
''' Sorts a list of type T.
''' </summary>
''' <typeparam name="T">The type of the objects in the list</typeparam>
''' <param name="context">The list</param>
''' <param name="sortExpression">The column to sort by</param>
''' <param name="sortDirection">The sort direction</param>
''' <returns>The sorted list</returns>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function Sort(Of T As {Class, New})(ByVal context As List(Of T), ByVal sortExpression As String, ByVal sortDirection As SortDirection) As IOrderedEnumerable(Of T)

    Dim param = Expression.Parameter(GetType(T), sortExpression.ToString)
    Dim field As PropertyInfo = GetColByName(Of T)(context, sortExpression)
    Dim keySelector = getKeySelector(Of T)(field)

    If sortDirection = WebControls.SortDirection.Ascending Then
        Return context.OrderBy(keySelector)
    Else
        Return context.OrderByDescending(keySelector)
    End If

End Function

''' <summary>
''' Get the property information of a named property against a class
''' </summary>
''' <returns>The property info of the primary key</returns>
''' <remarks>Throws an exception if no primary key exists</remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function GetColByName(Of T)(ByVal context As List(Of T), ByVal colname As String) As PropertyInfo
    Dim properties As PropertyInfo() = GetType(T).GetProperties()
    For Each pI As PropertyInfo In properties
        If pI.Name = colname Then
            Return pI
        End If
    Next
    Return Nothing
End Function

''' <summary>
''' Gets the key selector for a property on a generic class.
''' </summary>
''' <typeparam name="TSource">The class/type</typeparam>
''' <param name="property">the propertyinfo for the field</param>
''' <returns>the keyselector function</returns>
''' <remarks></remarks>
Function getKeySelector(Of TSource)([property] As PropertyInfo) As Func(Of TSource, Object)
    Return Function(item As TSource) [property].GetValue(item, Nothing)
End Function

End Module

答案 1 :(得分:1)

您可以使用OrderBy method of the list专门针对该列表使用内联函数。