代码之家  ›  专栏  ›  技术社区  ›  Matt Weldon

基于自定义对象中的ArrayList对列表进行排序

  •  1
  • Matt Weldon  · 技术社区  · 14 年前

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

    Public Rows As List(Of Row)()
    

    有2个属性, Key (字符串)和 Cells (排列列表)

    我需要能把每一个分类 在内部 Rows 基于开发人员定义的 细胞 ArrayList。

    例如,基于以下内容 S

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

    Rows.Sort(0) 将导致 Row2 成为世界第一 名单。实现这一点的最佳方法是什么?

    谢谢

    2 回复  |  直到 14 年前
        1
  •  1
  •   Mitchel Sellers    14 年前

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

    这里是一个 intro article 开始吧。

        2
  •  1
  •   Tim Schmelter    14 年前

    它类似于具有列的datrow,因此您可以使用DataView的排序功能(而不是IComparable解决方案):

    考虑动态创建一个数据表,其列作为单元格。 例如:

    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