对对象不为空的列表进行排序
我正在尝试对类列表进行排序,并且我需要具有子类的类,该子类在列表中不是第一个。我以为以下内容会起作用,但事实并非如此。
ListOfClasses.Sort(Function(x, y) If(x.SubClass IsNot Nothing, 1, 0))
我知道这充其量只是一个黑客(并不是说它有效),但我认为它会将类向上移动,使子类不等于任何东西?
I am trying to sort a list of classes, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
x
小于、等于或大于y
,您的比较器函数需要返回 -1、0 或 1。在您的情况下(因为您希望后面有Nothing
值):但请注意,在这里使用
Sort
效率很低。您需要的操作称为 partition 并以 O(n) 运行。Your comparer function needs to return -1, 0 or 1 if
x
is less than, equal to or greater thany
. In your case (since you want to haveNothing
values at the back):But be advised that using
Sort
here is unnecessarily inefficient. The operation you need is called partition and runs in O(n).这里的问题是您的比较器委托没有遵循 此处列出的正确比较规则。特别是,它需要确保如果您说“x 大于 y”,那么您也说“y 小于 x”。在这里,您只说过“x 大于 y”,但实际上从未说过相反的话。
这是一个比较器函数,它将正确对这些元素进行排序。
这也可以表示为语句 lambda,但由于它们仅在 Visual Studio 2010 中受支持,所以我选择编写完整的函数。
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
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.
如果您想要的只是最后的所有“Nothing”值(并且在这种情况下性能不是一个大问题),您可以在通用列表上使用默认的 .Sort() 。这将为您提供前面的“Nothing”值。然后你在列表上调用.Reverse。
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.