c# - 如何对包含文件大小数据的 ListView 列进行排序? C#

标签 c# winforms sorting listview

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

Type Data example:

最佳答案

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

    /// <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);
    }

关于c# - 如何对包含文件大小数据的 ListView 列进行排序? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6035815/

相关文章:

c# - t4 模板相对于 Class 文件的优势

c# - 从控制台调用的 Form.Show() 会卡住 GUI

c# - 模态对话框弹出后开始漫长的过程

c# - 变量中 Linq 查询的 Lambda 表达式

java - 如何在不使用 Collections.sort() 的情况下按值对 LinkedHashMap 进行排序?

c# - 如何阻止自定义性能计数器实例名称自动转换为小写

c# - 如何防止在图形对象上发生的 ExternalException

c# - 如何在 C# 中处理带有持续时间的实际时间?

c# - 无法使用与其底层 RCW 分离的 COM 对象

c# - IComparer无法正常工作