Sort List Where IsNot Nothing Object

I am trying to sort a list of classes, and I need classes with a subclass that is not the first in the list. I thought the following would work, but it is not.

ListOfClasses.Sort(Function(x, y) If(x.SubClass IsNot Nothing, 1, 0))

I know this is a hack at best (not that it works), but I thought it would move the classes up in order, where the subclass is not equal to anyone?

+3
source share
3 answers

, - , . , , , "x y", "y x". , "x y", .

,

Function Compare(ByVal x as TheType, ByVal y as TheType) As Integer
  If x.SubClass Is Nothing AndAlso y.SubClass Is Nothing Then
    Return 0
  Else If x.SubClass IsNot Nothing AndAlso y.SubClass IsNot Nothing Then
    Return 0
  Else If x.SubClass IsNot Nothing Tehn
    Return -1
  Else
    Return 1
  End If 
End Function

lambda, Visual Studio 2010, .

+2

-1, 0 1, x , , y. ( Nothing ):

Dim xNull = x Is Nothing
Dim yNull = y Is Nothing

If xNull = yNull Then Return 0 ' either both are Nothing, or neither is.
If xNull Then Return 1
Return -1

, Sort . partition O (n).

+3

If all you need is all the Nothing values ​​at the end (and performance in this case is not a big concern), you can use the standard .Sort () in the general list. This will give you “nothing” at the front. Then you call .Reverse on the list.

Dim ListOfClasses As New List(Of Object)
ListOfClasses.Add(Nothing)
ListOfClasses.Add("Something 1")
ListOfClasses.Add(Nothing)
ListOfClasses.Add("Something 2")
ListOfClasses.Add(Nothing)
ListOfClasses.Add("Something 3")

ListOfClasses.Sort()
ListOfClasses.Reverse()
0
source

Source: https://habr.com/ru/post/1795804/


All Articles