gpt4 book ai didi

.net - VB.NET 排序 IEnumerable 类

转载 作者:行者123 更新时间:2023-12-01 09:28:03 24 4
gpt4 key购买 nike

我想对一个实现 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”对象的地方太多了,所以我需要对“peopleList”进行排序,而不是对“People”的新排序列表。

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”。

最佳答案

您可以在创建 People 列表时对 Person 对象进行排序:

Public Sub New(ByVal pArray() As Person)
_people = New Person(pArray.Length - 1) {}

Dim i As Integer = 0
For
For Each person In pArray.OrderBy(Function(p) p.firstName)
_people(i) = person
i = i + 1
Next i
End Sub

或者,您可以提供自己的方法来在创建内部数组后对其进行排序。像这样的东西应该可以工作:

Public Class People
Public Sub Sort(Of T As IComparable)(KeySelector As Func(Of Person, T))
Array.Sort(_people, Function(x, y) KeySelector(x).CompareTo(KeySelector(y)))
End Sub
End Class

你可以这样称呼:

peopleList.Sort(Function(p) p.firstName)

关于.net - VB.NET 排序 IEnumerable 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19729535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com