首页 > 解决方案 > 此代码用于按列对列表视图中的项目进行排序,但它是如何工作的?

问题描述

我不久前在互联网上找到了以下代码,目前正在使用它按指定列对我的列表视图中的项目进行排序。虽然我知道代码的用途,但我不知道它实际上是如何工作的,有人可以告诉我吗?

Public Class ListViewItemComparer
Implements IComparer
Private column1 As Integer

Public Sub New()
    column1 = 0
End Sub

Public Sub New(ByVal column2 As Integer)
    column1 = column2
End Sub

Public Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare

    Dim result As Integer = [String].Compare(CType(x, ListViewItem).SubItems(column1).Text, CType(y, ListViewItem).SubItems(column1).Text)
    Return result
End Function                                                              
End Class

为了调用此代码,我目前正在执行以下操作:

lstvResults.ListViewItemSorter = New ListViewItemComparer([number of column I want to sort by], SortOrder.Ascending)

编辑:我设法找到我最初从哪里获得代码:https ://www.youtube.com/watch?time_continue=138&v=fRMztyQ06xI

标签: vb.netvisual-studio-2013

解决方案


这是 ListView 用于项目排序的类。它实现了 IComparer 接口,该接口有一个方法 Comparer.Compare,由 ListView 在内部调用以确定一个 ListViewItem 与另一个的相对位置。

Public Class ListViewItemComparer
Implements IComparer
    Private sortby As SortOrder ' Is this even used?
    Private column1 As Integer  ' Column by which to sort the ListViewItems.

    ' Default constructor: sort by the first column.
    Public Sub New()
        column1 = 0
    End Sub

    ' Parameterized constructor: sort by specified column (with SortOrder?).
    Public Sub New(ByVal column2 As Integer, ByVal sort_by As SortOrder)
        ' Change column sort on to column2.
        column1 = column2 
        sortby = sort_by
    End Sub

    ' Called internally by the ListView to sort its items.
    ' Indicates the position of ListViewItem x relative to ListViewItem y.
    ' Returns 
    '    Less-than-zero if the value of x's Text is less than y's.
    '    Zero if the value of x's Text is equal to y's.
    '    Greater-than-zero if the value of x's text is greater than y's.
    Public Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare

        ' To sort descending, you could flip the positions of x 
        ' and y in the String.Compare call.

        ' Cast x and y each to ListViewItem and compare the values 
        ' of their respective Text properties.
        Dim result As Integer = [String].Compare(CType(x, ListViewItem).SubItems(column1).Text, CType(y, ListViewItem).SubItems(column1).Text)
        Return result
    End Function                                                              
End Class

这可以在 ColumnClick 事件处理程序中用于更改 ListView 排序依据的列。

' ColumnClick event handler.
Private Sub ColumnClick(ByVal o as object, ByVal e as ColumnClickEventArgs)
    ' Set the ListViewItemSorter property to a new ListViewItemComparer 
    ' object. Setting this property immediately sorts the 
    ' ListView using the ListViewItemComparer object.
    Me.listView1.ListViewItemSorter = New ListViewItemComparer(e.Column, SortOrder.Ascending)
End Sub

推荐阅读