简体   繁体   English

VB .Net IComparer排序字符串,包括空格数字

[英]VB .Net IComparer sorting string that include blanks numerically

I have a datagridview databound string column that contain string numbers 0-99 and blank, nothing. 我有一个datagridview数据绑定字符串列,其中包含字符串编号0-99和空白,没有。

I wish to sort this column numerically 0 to 99 with either the blank nothing cells at the beginning or at the end. 我希望在数字上以0到99对该列进行排序,并且在开头或结尾处都是空白的单元格。

I use DataGridView_ColumnHeaderMouseClick event and check the column index to get the right one and then use an IComparer to sort. 我使用DataGridView_ColumnHeaderMouseClick事件并检查列索引以获取正确的索引,然后使用IComparer进行排序。

Class Colomn5Comparer : Implements IComparer
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim XX As DataGridViewRow = DirectCast(x, DataGridViewRow)
        Dim YY As DataGridViewRow = DirectCast(y, DataGridViewRow)
        If Not XX.Cells(5).Value = "" AndAlso Not YY.Cells(5).Value = "" Then

            If CInt(XX.Cells(5).Value) < CInt(YY.Cells(5).Value) Then

                If m_SortOrder = "Desc" Then
                    Return 1
                Else
                    Return -1
                End If

            ElseIf CInt(XX.Cells(5).Value) > CInt(YY.Cells(5).Value) Then

                If m_SortOrder = "Desc" Then
                    Return -1
                Else
                    Return 1
                End If

            Else
                Return 0
            End If

        Else
            Return 0
        End If

    End Function
End Class

I've had to excluded the cells with nothing blank values to prevent the greater or less then integer comparison from erroring 我不得不排除没有空白值的单元格,以防止误差大于或小于整数

 If Not XX.Cells(5).Value = "" AndAlso Not YY.Cells(5).Value = "" Then   

This of course leaves the blank nothing cells in their current row positions after sorting. 这当然会在排序后在当前行位置留下空白的单元格。

Is there a way I can include the nothing blank cells somehow in the sort so that they appear either at the bottom or the top of the sorted rows? 有没有办法可以在排序中以某种方式包含空白单元格,以便它们出现在排序行的底部或顶部?

刚刚找到答案,当排除空值时,如果我返回-1,它们将排序到开头。

some variation of this will give you more 一些变化会给你更多

If XX.Cells(5).Value = "" AndAlso  YY.Cells(5).Value = "" Then return 0;
If XX.Cells(5).Value = ""  Then return -1;
If YY.Cells(5).Value = ""  Then return +1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM