排序通用iCollection的扩展方法(Of T)

时间:2014-05-15 01:28:11

标签: vb.net linq sorting properties icollection

我试图按照我自己的标准扩展通用集合。

这就是我使用Linq的方式:

Dim sortedList = ViewCollection.OrderByDescending(Function(x) x.ViewName.Replace(" ", "").Replace(".", "").Trim.All(AddressOf Char.IsLetter)).ThenByDescending(Function(x) x.ViewName.Replace(" ", "").Replace(".", "").Trim.Any(AddressOf Char.IsDigit)).ThenBy(Function(x) x.ViewName.Replace(" ", "").Replace(".", "").Trim).ToList()

所以,这是我正在进行的排序方法扩展:

<System.Runtime.CompilerServices.Extension()> _
        Public Function SortCollection(Of T)(ByVal Collection As ICollection(Of T), ByVal PropertyName As String) As ICollection(Of T)

            For Each p As System.Reflection.PropertyInfo In Collection.GetType().GetProperties()
                If p.Name = PropertyName Then
                    result = Collection.ToList() ' I need to replace this with the sorting criteria posted above
                End If
            Next

            Return result
        End Function

我似乎找不到如何传递我想要使用的这个通用对象的属性作为字母排序标准的方法。

任何线索?

1 个答案:

答案 0 :(得分:1)

您需要获取PropertyDescriptor并使用此选项对集合进行排序。

<Extension()> _
Public Function Sort(Of T)(ByVal collection As IEnumerable(Of T), ByVal propertyName As String, direction As ListSortDirection) As IEnumerable(Of T)
    Dim descriptor As PropertyDescriptor = TypeDescriptor.GetProperties(GetType(T)).Find(propertyName, True)
    If (direction = ListSortDirection.Descending) Then
        Return (From item As T In collection Select item Order By descriptor.GetValue(item) Descending)
    Else
        Return (From item As T In collection Select item Order By descriptor.GetValue(item) Ascending)
    End If
End Function

<强>用法

MessageBox.Show(String.Join(Environment.NewLine, {"xxxxx", "xxx", "x", "xxxx", "xx"}.Sort("Length", ListSortDirection.Ascending)))

输出:

x
xx
xxx
xxxx
xxxxx