I have a table that has a column that is a class. How can I sort on that column.
The class implements IComaparable and IEquatable and does sort if stored in a list.
Printable View
I have a table that has a column that is a class. How can I sort on that column.
The class implements IComaparable and IEquatable and does sort if stored in a list.
I've never tried it but I would expect that, if your class implements IComparable, you would sort that column in exactly the same way as you would any other, e.g.
I would have expected that you would try that so I'm wondering whether you have an it didn't work.vb.net Code:
myDataTable.DefaultView.Sort = "MyColumn" 'Sort in default direction, which is ascending. myDataTable.DefaultView.Sort = "MyColumn ASC" 'Sort ascending. myDataTable.DefaultView.Sort = "MyColumn DESC" 'Sort descending.
I just did this in VS 2017:
When I ran the project, the grid displayed the three columns and I was able to click each column header to sort the grid exactly as expected. Can you not do the same? I also did this:vb.net Code:
Public Class Form1 Private table As New DataTable Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load With table.Columns .Add("Name", GetType(String)) .Add("Number", GetType(Integer)) .Add("Thing", GetType(Thing)) End With With table.Rows .Add("First", 1, New Thing With {.Name = "One"}) .Add("Second", 2, New Thing With {.Name = "Two"}) .Add("Third", 3, New Thing With {.Name = "Three"}) .Add("Fourth", 4, New Thing With {.Name = "Four"}) .Add("Fifth", 5, New Thing With {.Name = "Five"}) .Add("Sixth", 6, New Thing With {.Name = "Six"}) .Add("Seventh", 7, New Thing With {.Name = "Seven"}) .Add("Eighth", 8, New Thing With {.Name = "Eight"}) .Add("Ninth", 9, New Thing With {.Name = "Nine"}) .Add("Tenth", 10, New Thing With {.Name = "Ten"}) End With DataGridView1.DataSource = table End Sub End Class Public Class Thing Implements IComparable, IComparable(Of Thing), IEquatable(Of Thing) Public Property Name As String Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Return CompareTo(DirectCast(obj, Thing)) End Function Public Function CompareTo(other As Thing) As Integer Implements IComparable(Of Thing).CompareTo Return Name.CompareTo(other.Name) End Function Public Overloads Function Equals(other As Thing) As Boolean Implements IEquatable(Of Thing).Equals Return Name.Equals(other.Name) End Function Public Overrides Function ToString() As String Return Name End Function End Class
and those Buttons worked exactly as expected.vb.net Code:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click table.DefaultView.Sort = "Thing ASC" End Sub Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click table.DefaultView.Sort = "Thing DESC" End Sub
What happens with my thing, that sounds bad ;), is that the .ToString method is being called, and not the ICompare interface.