How to sort a listview column that contains file size data? C#

后端 未结 3 877
时光取名叫无心
时光取名叫无心 2021-01-14 20:59

I want to sort the items inside column of ListView, i already made it, but... i can\'t made it with the type of data in column (see picture), someone knows the way for do it

3条回答
  •  春和景丽
    2021-01-14 21:47

    Write a custom comparator for the sort function, like this:

        /// 
        /// Comparator for values like 123 KB
        /// 
        /// First value to compare
        /// Second value to compare
        /// 0 for equal, 1 for x > y, -1 for x < y
        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);
        }
    

提交回复
热议问题