【问题标题】:How to sort a listview column that contains file size data? C#如何对包含文件大小数据的列表视图列进行排序? C#
【发布时间】:2011-08-27 12:11:04
【问题描述】:

我想对ListView列内的项目进行排序,我已经做到了,但是......我不能用列中的数据类型(见图),有人知道怎么做吗?

【问题讨论】:

  • @alexn:你为什么要删除我问题的开头?。
  • 什么平台? Windows 窗体? WPF? ASP.NET?此外,它是如何填充的?像阅读别人的问题一样阅读问题,然后添加您认为缺失的缺失细节。
  • 数据是什么类型的?这些只是数字后缀“KB”的字符串吗?
  • @Krahne:一般准则规定在问题中添加问候和感谢是一种不好的做法。 (stackoverflow.com/faq)
  • @decyclone:哦,对不起,我忘了;嗯...是 Windows 窗体。

标签: c# winforms sorting listview


【解决方案1】:

创建listViewSizeSorter类扩展Icomparer接口如下。

using System.Collections;
using System.Windows.Forms;

namespace MyNameSpace
{
    /// <summary>
    /// This class is an implementation of the 'IComparer' interface.
    /// </summary>
    public class ListViewSizeSorter : IComparer
    {
        /// <summary>
        /// Specifies the column to be sorted
        /// </summary>
        private int _columnToSort;
        /// <summary>
        /// Specifies the order in which to sort (i.e. 'Ascending').
        /// </summary>
        private SortOrder _orderOfSort;

        /// <summary>
        /// Class constructor.  Initializes various elements
        /// </summary>
        public ListViewSizeSorter()
        {
            // Initialize the column to '0'
            SortColumn = 0;

            // Initialize the sort order to 'none'
            Order = SortOrder.None;
        }

        /// <summary>
        /// This method is inherited from the IComparer interface.  It compares the two objects passed using a case insensitive comparison.
        /// </summary>
        /// <param name="x">First object to be compared</param>
        /// <param name="y">Second object to be compared</param>
        /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
        public int Compare(object x, object y)
        {
            var listviewX = (ListViewItem)x;
            var listviewY = (ListViewItem)y;
            string strX = listviewX.SubItems[_columnToSort].Text;
            string strY = listviewY.SubItems[_columnToSort].Text;

            // Nulls first (null means less, since it's blank)
            if (strX == null)
            {
                if (strY == null)
                    return 0;
                return -1;
            }
            if (strY == null)
                return 1;

            // Convert the non-KB part to a number
            double numX = 0;
            double numY = 0;
            if (strX.EndsWith("KB") || strX.EndsWith("GB") || strX.EndsWith("MB"))
                double.TryParse(strX.Substring(0, strX.Length - 3), out numX);
            if (strX.EndsWith("Bytes"))
                double.TryParse(strX.Substring(0, strX.Length - 6), out numX);
            if (strY.EndsWith("KB") || strY.EndsWith("GB") || strY.EndsWith("MB"))
                double.TryParse(strY.Substring(0, strY.Length - 3), out numY);
            if (strY.EndsWith("Bytes"))
                double.TryParse(strX.Substring(0, strY.Length - 6), out numY);
            long bytesX;
            long bytesY;
            if (strX.EndsWith("KB"))
                bytesX = (long)numX * 1024;
            else if (strX.EndsWith("MB"))
                bytesX = (long)numX * 1048576;
            else if (strX.EndsWith("GB"))
                bytesX = (long)numX * 1073741824;
            else
                bytesX = (long) numX;

            if (strY.EndsWith("KB"))
                bytesY = (long)numY * 1024;
            else if (strY.EndsWith("MB"))
                bytesY = (long)numY * 1048576;
            else if (strY.EndsWith("GB"))
                bytesY = (long)numY * 1073741824;
            else
                bytesY = (long) numY;

            var compareResult = bytesX.CompareTo(bytesY);

            if (_orderOfSort == SortOrder.Ascending)
            {
                // Ascending sort is selected, return normal result of compare operation
                return compareResult;
            }
            if (_orderOfSort == SortOrder.Descending)
            {
                // Descending sort is selected, return negative result of compare operation
                return (-compareResult);
            }
            // Return '0' to indicate they are equal
            return 0;
        }

        /// <summary>
        /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
        /// </summary>
        public int SortColumn
        {
            set
            {
                _columnToSort = value;
            }
            get
            {
                return _columnToSort;
            }
        }

        /// <summary>
        /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
        /// </summary>
        public SortOrder Order
        {
            set
            {
                _orderOfSort = value;
            }
            get
            {
                return _orderOfSort;
            }
        }
    }
}

用你的名字改变命名空间。

在表单中添加以下行。

private readonly ListViewSizeSorter _listViewSizeSorter;
        public Form1()
        {
            InitializeComponent();
            _listViewSizeSorter = new ListViewSizeSorter {SortColumn = 1};
        }

private void ListViewFilesColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == _listViewColumnSorter.SortColumn)
            {
                if(e.Column.Equals(1))
                {
                    listViewFiles.ListViewItemSorter = _listViewSizeSorter;
                    // Reverse the current sort direction for this column.
                    _listViewSizeSorter.Order = _listViewSizeSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                _listViewColumnSorter.SortColumn = e.Column;
                _listViewColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            listViewFiles.Sort();
        }

【讨论】:

    【解决方案2】:

    你试过Microsoft has to say这个任务吗?基本上,您必须实现自定义比较器,并处理 ColumnClick 事件。但由于列表视图中的项目存储为字符串,您很可能需要进行一些解析(假设您想按大小排序),或实施解决方法 - 排序数据源并重新分配项目(这可能更容易)。

    解决方法的伪代码的快速示例(因为从涉及的字符串解析实现自定义比较器对于这样简单的任务来说似乎太麻烦了)。在ColumnClick 事件处理程序中,您可以这样做:

    // I assume you got list of raw dll sizes somewhere
    dllSizes.Sort();
    List<ListViewItem> dllSizesForDisplay = new List<ListViewItem>();
    foreach (var dll in dllSizes)
    {
        dllSizes.Add(new ListViewItem(GetSize(dll.Bytes)));
    }
    
    // reasign items
    listView.Items.Clear();
    listView.Items.AddRange(dllSizesForDisplay);
    

    【讨论】:

      【解决方案3】:

      为排序函数编写一个自定义比较器,如下所示:

          /// <summary>
          /// Comparator for values like 123 KB
          /// </summary>
          /// <param name="x">First value to compare</param>
          /// <param name="y">Second value to compare</param>
          /// <returns>0 for equal, 1 for x &gt; y, -1 for x &lt; y</returns>
          int Compare(object x, object y)
          {
              // Convert to strings
              string strX = null;
              if (x is string)
                  strX = (string)x;
              else if (x != null)
                  strX = x.ToString();
              string strY = null;
              if (y is string)
                  strY = (string)y;
              else if (y != null)
                  strY = y.ToString();
      
              // Nulls first (null means less, since it's blank)
              if (strX == null)
              {
                  if (strY == null)
                      return 0;
                  return -1;
              }
              else if (strY == null)
                  return 1;
      
              // Convert the non-KB part to a number
              double numX;
              double numY;
              if (strX.EndsWith("KB") || strX.EndsWith("GB") || strX.EndsWith("MB"))
                  strX = strX.Substring(0, strX.Length - 2);
              if (strX.EndsWith("Bytes"))
                  strX = strX.Substring(0, strX.Length - 5);
              strX = strX.Trim();
              double.TryParse(strX, out numX);
              if (strY.EndsWith("KB") || strY.EndsWith("GB") || strY.EndsWith("MB"))
                  strY = strY.Substring(0, strY.Length - 2);
              if (strY.EndsWith("Bytes"))
                  strY = strX.Substring(0, strY.Length - 5);
              strY = strY.Trim();
              double.TryParse(strY, out numY);
      
              // Compare the numbers
              return numX.CompareTo(numY);
          }
      

      【讨论】:

      • 老兄...我快疯了,我从来没有使用过 IComparer 界面,所以...如果你能帮助我(比你做的更多)请告诉我如何使用它,或者在哪里...非常感谢,并且...原谅我的无知,但这是我第一次使用这个界面(iComparer)。
      • 这取决于您使用数据的方式。您是在使用 DataBinding,还是自己对集合进行排序?
      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 2017-09-08
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2020-12-27
      相关资源
      最近更新 更多