如何在VB.Net中对System.Collections.Generic.List进行排序?

Nak*_*ary 30 .net vb.net sorting

我使用genric列表(m_equipmentList),它是对象的集合(Schedule_Payitem).
如何根据子对象的权利排序列表?

Dim m_equipmentList As New List(Of Schedule_Payitem)
Run Code Online (Sandbox Code Playgroud)

需要根据Schedule_Payitem的resourceid属性对m_equipmentList进行排序.

Jon*_*eet 56

你在用VB9吗?如果是这样,我会使用lambda表达式创建一个Comparer(Of Schedule_PayItem).否则,写一个简短的类来实现IComparer(Of Schedule_PayItem).通过你进入List.Sort的任何一个.

lambda表达式的示例(未经测试):

m_equipmentList.Sort(Function(p1, p2) p1.ResourceID.CompareTo(p2.ResourceID))
Run Code Online (Sandbox Code Playgroud)

对于IComparer(Of Schedule_PayItem):

Public Class PayItemResourceComparer
    Implements IComparer(Of Schedule_PayItem)
    Public Function Compare(ByVal p1 As Schedule_PayItem, _
                            ByVal p2 As Schedule_PayItem) As Integer
        Return p1.ResourceID.CompareTo(p2.ResourceID)
    End Function
End Class

...

m_equipmentList.Sort(New PayItemResourceComparer)
Run Code Online (Sandbox Code Playgroud)

  • 有用的提示指定Collections.Generic.IComparer(Of Schedule_PayItem).我收到一个错误:'System.Collections.IComparer'没有类型参数.一点点搜索帮助我发现存在两个具有相同名称的接口,一个在System.Collections中,另一个在System.Collections.Generic中. (4认同)

Pab*_*tyk 7

我不知道vb.net,所以我在C#中做到了

m_equipmentList.Sort(
   (payItem1,payItem2)=>payItem1.ResourceID.CompareTo(payItem2.ResourceID));
Run Code Online (Sandbox Code Playgroud)

并使用反射器将其翻译为vb.net希望它有所帮助

m_equipmentList.Sort(
Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
    Return payItem1.ResourceID.CompareTo(payItem2.ResourceID)
End Function)
Run Code Online (Sandbox Code Playgroud)

或者您可以从IComparable继承Schedule_Payitem并实现CompareTo然后只需调用 m_equipmentList.Sort()


小智 5

您可以通过更改以下内容按降序完成对列表的排序 -

m_equipmentList.Sort(
Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
    Return payItem1.ResourceID.CompareTo(payItem2.ResourceID)
End Function)
Run Code Online (Sandbox Code Playgroud)

对此

m_equipmentList.Sort(
Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
    Return payItem2.ResourceID.CompareTo(payItem1.ResourceID)
End Function)
Run Code Online (Sandbox Code Playgroud)