【问题标题】:Extension method for Sorting a generic iCollection(Of T)对泛型 iCollection(Of T) 进行排序的扩展方法
【发布时间】:2014-05-15 01:28:11
【问题描述】:

我正在尝试扩展一个通用集合,使其可以按我自己的标准进行排序。

这就是我使用 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

我似乎无法找到一种方法来传递我想要使用的通用对象的哪些属性作为字母排序标准。

有什么线索吗?

【问题讨论】:

    标签: vb.net linq sorting properties icollection


    【解决方案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
    

    【讨论】:

    • 非常感谢伙计,我会试一试,但它似乎非常接近我想要的。我只需要满足嵌套属性以及“View.Name”之类的需求,因此我将研究如何嵌套表达式。但这非常接近。干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2014-12-21
    • 1970-01-01
    相关资源
    最近更新 更多