IEnumerable を実装する VB クラスをソートしたいと考えています。新しいオブジェクト/linqは必要ありません。元のオブジェクトのままにしておく必要がありますが、並べ替えます。これがサンプルクラスです。
Public Class Person
Public Sub New(ByVal fName As String, ByVal lName As String)
Me.firstName = fName
Me.lastName = lName
End Sub
Public firstName As String
Public lastName As String
End Class
Public Class People
Implements IEnumerable(Of Person)
Private _people() As Person
Public Sub New(ByVal pArray() As Person)
_people = New Person(pArray.Length - 1) {}
Dim i As Integer
For i = 0 To pArray.Length - 1
_people(i) = pArray(i)
Next i
End Sub
Public Function GetEnumerator() As IEnumerator(Of Person) _
Implements IEnumerable(Of Person).GetEnumerator
Return DirectCast(_people, IEnumerable(Of Person)).GetEnumerator
End Function
Private Function System_Collections_GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return Me.GetEnumerator
End Function
End Class
LINQ を使用できることはわかっていますが、元のオブジェクトではなく新しいオブジェクトがソートされます。グローバルな「peopleList」オブジェクトを使用する場所が多すぎるため、「People」の新しいソート済みリストではなく、「peopleList」をソートする必要があります。
Dim peopleList As New People({ _
New Person("John", "Smith"), _
New Person("Jim", "Johnson"), _
New Person("Sue", "Rabon")})
Dim newPeopleList = From person In peopleList Order By person.firstName Select person
'OR
Dim newPeopleList = DirectCast(peopleList, IEnumerable(Of Person)).ToList()
newPeopleList.Sort(Function(p1, p2) p1.firstName.CompareTo(p2.firstName))
次のようなものがもっと必要です。
Dim peopleList As New People({ _
New Person("John", "Smith"), _
New Person("Jim", "Johnson"), _
New Person("Sue", "Rabon")})
peopleList = peopleList.Sort(Function(p) p.firstName)
IEnumerable に Sort メソッドがないことはわかっています。例として示しているだけです。「People」クラスを変更するオプションはありますが、現在の呼び出し元を壊したくないため、最終的には引き続き IEnumerable を実装する必要があります。また、現在の発信者は、ソートされた「peopleList」を確認できる必要があります。