开发者

Sort List where object IsNot Nothing

I am trying to sort a list of c开发者_开发技巧lasses, and I need the classes with a subclass that isnot nothing first in the list. I thought the following would work but it doesnt.

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 the order where the subclass was not equal to nothing?


Your comparer function needs to return -1, 0 or 1 if x is less than, equal to or greater than y. In your case (since you want to have Nothing values at the back):

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

But be advised that using Sort here is unnecessarily inefficient. The operation you need is called partition and runs in O(n).


The problem here is that your comparer delegate doesn't follow the proper comparison rules as listed here. In particular it needs to ensure that if you say 'x is greater than y' that you also say 'y is less than x'. Here you're only ever saying 'x is greater than y' but you never actually say the opposite.

Here is a comparer function that will properly sort these elements

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

This could also be expressed as a statement lambda but as they're only supported in Visual Studio 2010 I chose to write a full function.


If all you want is all of the 'Nothing' values at the end (and performance isn't a huge concern in this situation) you can use the default .Sort() on a generic list. This will give you the 'Nothing' values 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜