簡體   English   中英

如何在VB.Net中對System.Collections.Generic.List進行排序?

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

我使用genric列表(m_equipmentList),它是對象的集合(Schedule_Payitem)。
如何根據子對象的權利排序列表?

Dim m_equipmentList As New List(Of Schedule_Payitem)

需要根據Schedule_Payitem的resourceid屬性對m_equipmentList進行排序。

你在用VB9嗎? 如果是這樣,我將使用lambda表達式來創建Comparer(Of Schedule_PayItem) 否則,編寫一個短類來實現IComparer(Of Schedule_PayItem) 通過你進入List.Sort的任何一個。

lambda表達式的示例(未經測試):

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

對於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)

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

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

並使用反射器將其翻譯為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_Payitem並實現CompareTo然后只需調用m_equipmentList.Sort()

您可以通過更改以下內容按降序完成對列表的排序 -

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)

試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM