我想排序一个实现IEnumerable的VB类。 我不想要一个新的对象/ linq。 它必须保持原始对象,但排序。 这是一个示例类。VB.NET排序IEnumerable类
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”进行排序,而不是一个新的“人物”排序列表。
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”。
这是一个选项,但在查询对象之前,其他一些方法会填充对象。因此,某种“Sort”方法/功能会更好。像这样的东西http://danielsaidi.wordpress.com/2009/08/27/sort-ienumerable-and-list-with-property-name/,但在VB中。 – goroth
@goroth查看我的更新答案替代 –
我喜欢更新的答案,但它不能在我的机器上使用.NET 3.5进行编译...行Func(Person,T) - “数组边界不能出现在类型说明符中“ – goroth