编辑代码以按降序数字顺序排列列表框项目

时间:2016-03-12 00:18:58

标签: vb.net winforms visual-studio-2013 listbox

我正在尝试为该项目生成报告,该报告显示哪些县(科克,卡洛等)最受欢迎。目前,我已经能够找到客户县的每次迭代,并将其显示在列表框(lstReports)中,如此...

Antrim= 0
Armagh= 1
Carlow= 2
Cavan=  1

依此类推

我想通过点击按钮来实现,我可以按数字加入顺序(btnNumericAc)和降序(btnNumericdec)对列表进行排序......

例如。 Accending

Antrim= 0
Armagh= 1
Cavan= 1
Carlow= 2

e.g。 Decending

Carlow= 2
Armagh= 1
Cavan= 1
Antrim= 0

我能够找到一条通过升序命令我的项目的代码,我想知道我需要通过降序对代码进行编辑。没有关于代码如何工作的解释,所以我不确定要做什么编辑。

代码:

班级代码:

Public Class CountiesSorter 
Implements IComparer(Of String)

Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements System.Collections.Generic.IComparer(Of String).Compare
    Dim xai As Integer = x.IndexOf(" ")
    Dim yai As Integer = y.IndexOf(" ")
    Select Case True
        Case xai = -1 AndAlso yai = -1
            Return x.CompareTo(y)
        Case xai = -1 AndAlso yai > -1
            Return -1
        Case xai > -1 AndAlso yai = -1
            Return +1
        Case xai > -1 AndAlso yai > -1
            Dim xs As String() = x.Split(" ")
            Dim ys As String() = y.Split(" ")
            Select Case xs(1).CompareTo(ys(1))
                Case 0 : Return xs(0).CompareTo(ys(0))
                Case -1 : Return -1
                Case +1 : Return +1
            End Select
    End Select
End Function
End Class

功能代码:

Public Sub SortAccendingListBox(ByRef lb As ListBox)
    Dim il As New List(Of String)
    For Each i As String In lb.Items
        il.Add(i)
    Next
    il.Sort(New CountiesSorter)
    lb.Items.Clear()
    lb.Items.AddRange(il.ToArray)
End Sub

按钮代码:

Private Sub btnNumericAs_Click(sender As Object, e As EventArgs) Handles btnNumericAs.Click
SortAccendingListBox(lstReports)
End Sub

感谢您的帮助和时间。

1 个答案:

答案 0 :(得分:1)

创建一个包含CountyName的{​​{1}}课程 然后创建一个Popularity并填写县 然后使用List<Conuty>OrderBy(x=>x.Popularity)对其进行排序。然后将排序结果设置为OrderByDescending(x=>x.Popularity)的{​​{1}}。

<强>代码

以下是DataSource类的代码:

ListBox

以下是County的代码:

Public Class County
    Public Property Name As String
    Public Property Popularity As Integer
    Public Overrides Function ToString() As String
        Return String.Format("{0}= {1}", Me.Name, Me.Popularity)
    End Function
End Class