如何排序包含文件大小的数据列表视图的列? C# [英] How to sort a listview column that contains file size data? C#
本文介绍了如何排序包含文件大小的数据列表视图的列? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想里面的ListView列中的项目进行排序,我已经做到了,但......我不能与数据的列(见图片)型成功了,有人知道了道路呢?
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?
推荐答案
写的排序功能的自定义比较,类似这样的:
Write a custom comparator for the sort function, like this:
/// <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 > y, -1 for x < 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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文