【问题标题】:Sorting a List based on an ArrayList within a custom Object根据自定义对象中的 ArrayList 对列表进行排序
【发布时间】:2010-05-24 14:27:19
【问题描述】:

我正在使用一个列表来跟踪一些自定义Row 对象,如下所示:

Public Rows As List(Of Row)()

Row 有 2 个属性,Key(一个字符串)和Cells(一个数组列表)。

我需要能够根据开发人员定义的Cells ArrayList 索引对Rows 中的每个Row 进行排序。

所以例如基于以下Rows

Row1.Cells = ("b", "12")
Row2.Cells = ("a", "23")

Rows.Sort(0) 将导致Row2Rows 列表中排在第一位。实现这一点的最佳方法是什么?

谢谢

【问题讨论】:

    标签: vb.net sorting .net-2.0


    【解决方案1】:

    如果您在 Row 对象上实现 IComparable,则可以定义自定义比较过程,以便能够进行所需的排序。

    这里是intro article,可以帮助您入门。

    【讨论】:

    • 感谢您,IComparable 对我的Row 对象进行了一些调整。
    • 很高兴它有帮助,前几次有点棘手,但对这些自定义排序项很有帮助
    【解决方案2】:

    它类似于带有列的 DatRow,因此您可以替代(替代 IComparable 解决方案)使用 DataView 的排序能力:

    考虑动态创建一个 DataTabale,并将其列作为您的单元格。 例如:

    Dim rows As New List(Of Row)
    Dim row = New Row("Row 1")
    Dim cell1 As New Row.Cell("b")
    Dim cell2 As New Row.Cell("12")
    row.Cells.Add(cell1)
    row.Cells.Add(cell2)
    rows.Add(row)
    row = New Row("Row 2")
    cell1 = New Row.Cell("a")
    cell2 = New Row.Cell("23")
    row.Cells.Add(cell1)
    row.Cells.Add(cell2)
    rows.Add(row)
    
    Dim tbl As New DataTable()
    ''#are the cell count in every row equal? Otherwise you can calculate the max-count
    Dim cellCount As Int32 = 2 ''#for example
    For i As Int32 = 0 To cellCount - 1
        Dim newCol As New DataColumn("Column " & i + 1)
        tbl.Columns.Add(newCol)
    Next
    For rowIndex As Int32 = 0 To rows.Count - 1
        row = rows(rowIndex)
        Dim newRow As DataRow = tbl.NewRow
        For cellIndex As Int32 = 0 To row.Cells.Count - 1
            Dim cell As Row.Cell = row.Cells(cellIndex)
            newRow(cellIndex) = cell.value
        Next
        tbl.Rows.Add(newRow)
    Next
    Dim view As New DataView(tbl)
    view.Sort = "Column 1"
    ''#you can use the view as datasource or other purposes
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      相关资源
      最近更新 更多