How sort a System.Collections.Generic.List in VB.Net?

前端 未结 4 1268
悲&欢浪女
悲&欢浪女 2021-01-31 09:23

I using a genric list(m_equipmentList ) which is collection of objects (Schedule_Payitem).
How can sort list according to a proerty of child object ?

Dim m_         


        
相关标签:
4条回答
  • 2021-01-31 09:27

    Are you using VB9? If so, I'd use a lambda expression to create a Comparer(Of Schedule_PayItem). Otherwise, write a short class to implement IComparer(Of Schedule_PayItem). pass whichever one you've got into List.Sort.

    An example for the lambda expression (untested):

    m_equipmentList.Sort(Function(p1, p2) p1.ResourceID.CompareTo(p2.ResourceID))
    

    And for the 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)
    
    0 讨论(0)
  • 2021-01-31 09:27

    Try this

    Dim m_equipmentList As New List(Of Schedule_Payitem)
    
    
    m_equipmentList.Sort(delegate(Schedule_Payitem p1, Schedule_Payitem p2)
                  {
                      return p1.resourceid .CompareTo(p2.resourceid );
                  });
    
    0 讨论(0)
  • 2021-01-31 09:50

    I don't know vb.net so I did it in C#

    m_equipmentList.Sort(
       (payItem1,payItem2)=>payItem1.ResourceID.CompareTo(payItem2.ResourceID));
    

    and using the reflector translated it to vb.net hope it helps

    m_equipmentList.Sort(
    Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
        Return payItem1.ResourceID.CompareTo(payItem2.ResourceID)
    End Function)
    

    or you can inherit Schedule_Payitem from IComparable and implement CompareTo and then just call m_equipmentList.Sort()

    0 讨论(0)
  • 2021-01-31 09:52

    You can accomplish sorting the list in descending order by changing this-

    m_equipmentList.Sort(
    Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
        Return payItem1.ResourceID.CompareTo(payItem2.ResourceID)
    End Function)
    

    to this

    m_equipmentList.Sort(
    Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
        Return payItem2.ResourceID.CompareTo(payItem1.ResourceID)
    End Function)
    
    0 讨论(0)
提交回复
热议问题