从继承基类的不同类的对象列表中排序 - VB.Net

时间:2014-04-20 12:54:50

标签: vb.net list sorting inheritance base-class

我在VB.net工作但是.Net或者基础知识中的任何例子都会受到赞赏。我有几个继承相同基类的类。在基类中有一个integer类型的属性。我想根据基类中的这个属性对各个类的几个列表进行排序。我熟悉.Sort使用共享函数的地址来排序对象列表。我遇到的问题是有几个不同类的不同列表,我想将它们全部排序为一个大的列表。对于任何反馈,我们都表示感谢。 谢谢。大卫

2 个答案:

答案 0 :(得分:1)

听起来很适合在你的基类中实现IComparable,然后在列表中使用包含从基类派生的所有对象的.Sort()方法:

Class MyClass
    Implements IComparable(Of MyClass)

    Private m_MySortValue As Integer

    #Region "IComparable<MyClass> Members"

    Public Function CompareTo(other As MyClass) As Integer
        If Me.m_MySortValue < other.m_MySortValue Then
            Return -1
        ElseIf Me.m_MySortValue > other.m_MySortValue Then
            Return 1
        Else
            Return 0
        End If
    End Function

    #End Region
End Class

如果您需要在排序之前将所有对象放入一个大列表中,您可以使用Concat或只创建一个新列表并使用AddRange添加其他列表中的所有元素。

答案 1 :(得分:0)

以下是基类的转换派生类的示例:

示例类:

Public Class Book
    Inherits Item
    Public Property Author As String = ""
End Class
Public Class Tape
    Inherits Item
    Public Property Artist As String = ""
End Class
Public Class Item
    Public Property Name As String = ""
    Public Property Price As Double = 0.0
    Public Property Quantity As Double = 0.0
    Public Overloads Function ToString() As String
        Return Price.ToString
    End Function
End Class

代码:

Dim list1 As New List(Of Book)(
{
    New Book With {.Price = 1.0},
    New Book With {.Price = 2.0}
    })

Dim list2 As New List(Of Tape)(
    {
        New Tape With {.Price = 3.0},
        New Tape With {.Price = 0.95}
    })
Dim list3 As List(Of Item) = (From item1 In New List(Of Item)(list1).Concat(list2)
                                Order By item1.Price
                                Select item1).ToList

这将从派生类返回基类列表,该派生类按基类中的特定属性排序。需要注意的是,新列表是基类类型,并且不具有派生类的任何特定属性/方法。

相关问题