views:

84

answers:

2

I am using a list to keep track of a number of custom Row objects as follows:

Public Rows As List(Of Row)()

Row has 2 properties, Key (a String) and Cells (an ArrayList).

I need to be able to sort each Row within Rows based on a developer defined index of the Cells ArrayList.

So for example based on the following Rows

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

Rows.Sort(0) would result in Row2 being first in the Rows list. What would be the best way of going about implementing this?

Thanks

+1  A: 

If you implement IComparable on your Row object, you can define a custom comparison process to be able to do the sorting that you desire.

Here is an intro article to get you started.

Mitchel Sellers
Thanks for that, IComparable works a treat with a little bit of tweaking to my `Row` object.
Matt Weldon
Glad it helped, the first few times it is a bit tricky, but very helpful for these custom sort items
Mitchel Sellers
+1  A: 

Its similar to a DatRow with it's Columns, so you can alternative(to the IComparable solution) use the sort-ability of a DataView:

Consider creating a DataTabale on the fly with its columns as your cells. For example:

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
Tim Schmelter