【问题标题】:VB .Net IComparer sorting string that include blanks numericallyVB .Net IComparer 排序字符串,包括数字空格
【发布时间】:2015-02-14 12:33:57
【问题描述】:

我有一个 datagridview 数据绑定字符串列,其中包含字符串数字 0-99 和空白,什么都没有。

我希望对这一列进行数字排序,从 0 到 99,在开头或结尾使用空白单元格。

我使用 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

我不得不排除没有空白值的单元格,以防止大于或小于整数比较出错

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

这当然会在排序后将空白单元格留在当前行位置。

有没有办法可以在排序中以某种方式包含空白单元格,以便它们出现在排序行的底部或顶部?

【问题讨论】:

    标签: .net vb.net sorting icomparer


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这方面的一些变化会给你更多

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-13
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 2016-12-26
        • 2015-07-06
        • 1970-01-01
        相关资源
        最近更新 更多