.net - 对象不为空的排序列表

标签 .net vb.net generics list lambda

我正在尝试对类列表进行排序,我需要具有子类的类在列表中不是什么都不是。我认为以下内容会起作用,但它不起作用。

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

我知道这充其量只是一种 hack(不是它有效),但我认为它会将类提升到子类不等于无的顺序?

最佳答案

如果 x 小于、等于或大于 y,您的比较器函数需要返回 -1、0 或 1。在你的情况下(因为你想在后面有 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) 中运行。

关于.net - 对象不为空的排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5171256/

相关文章:

c# - 在 P/Invoke 调用上固定 char[]

c# - 在多个线程上运行 COM 组件控件

c++ - 快速将 "MFC Extension DLL"转换为 "Regular DLL with MFC statically linked"

vb.net - 将字符串传递给 VB.net 中的对话框

java - Object.getClass() 方法的签名

c# - 绘制 2 条线

.net - Style BasedOn 突然不起作用

c# - .net 中的透明用户控制

c# - 当 T 未知时,如何使用反射执行 List<object>.Cast<T>

JavaFX FilteredList 泛型 getPredicate()