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

如何在VB.Net中对System.Collections.Generic.List进行排序?,.net,vb.net,sorting,.net,Vb.net,Sorting,我使用一个genric列表(m_equipmentList),它是对象的集合(Schedule_Payitem)。 如何根据子对象的属性对列表进行排序 Dim m_equipmentList As New List(Of Schedule_Payitem) 需要根据Schedule\u Payitem的resourceid属性对m\u equipmentList进行排序。试试这个 Dim m_equipmentList As New List(Of Schedule_Payitem) m_

我使用一个genric列表(m_equipmentList),它是对象的集合(Schedule_Payitem)。
如何根据子对象的属性对列表进行排序

Dim m_equipmentList As New List(Of Schedule_Payitem)
需要根据Schedule\u Payitem的resourceid属性对m\u equipmentList进行排序。

试试这个

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 );
              });

我不懂vb.net,所以我用C#

使用反射器将其转换为vb.net,希望对您有所帮助

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

或者您可以从IComparable继承Schedule\u Payitem并实现CompareTo,然后只需调用
m\u equipmentList.Sort()

是否使用VB9?如果是这样的话,我将使用创建一个
比较器(属于Schedule\u PayItem)
。否则,编写一个简短的类来实现
IComparer(属于Schedule\u PayItem)
。把任何一个都传给List.Sort

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

对于
i公司(附表付款项目)


通过更改此选项,可以按降序对列表进行排序-

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

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

VB.Net在vs2008之前不支持匿名委托,因此此代码的转换可能并不简单。您的代码是C#和VB.Net的混合体行尾的字符代表C#!谢谢你问这个问题。我能够在我的一个项目中使用Jon Skeet的lambda表达式。指定集合的有用提示。Generic.IComparer(Schedule_PayItem的)。我收到一个错误:“System.Collections.IComparer”没有类型参数。稍微搜索一下,我发现存在两个同名的接口,一个在System.Collections中,另一个在System.Collections.Generic中。这是解决很多问题的好方法:D
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)
m_equipmentList.Sort(
Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
    Return payItem1.ResourceID.CompareTo(payItem2.ResourceID)
End Function)
m_equipmentList.Sort(
Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem) 
    Return payItem2.ResourceID.CompareTo(payItem1.ResourceID)
End Function)