我正在使用一个列表来跟踪一些自定义Row
对象,如下所示:
Public Rows As List(Of Row)()
Row
有2个属性,Key
(一个字符串)和Cells
(一个ArrayList)。
我需要能够根据开发人员定义的Row
ArrayList索引对Rows
内的每个Cells
进行排序。
例如,基于以下Row
s
Row1.Cells = ("b", "12")
Row2.Cells = ("a", "23")
Rows.Sort(0)
会导致Row2
列在Rows
列表中。实现这个目标的最佳方式是什么?
由于
答案 0 :(得分:1)
如果在Row对象上实现IComparable,则可以定义自定义比较过程,以便能够进行所需的排序。
这是intro article,可以帮助您入门。
答案 1 :(得分:1)
它类似于带有Columns的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