简体   繁体   English

如何按文件大小对列表视图进行排序?

[英]How to sort a listview by file size?

I have a listview with 4 columns - Name, Extension, Size and Location. 我有一个包含4列的列表视图-名称,扩展名,大小和位置。 I have a method that takes the file size in bytes and converts to KB, MB, GB, etc as needed. 我有一种方法,该方法以字节为单位获取文件大小,然后根据需要转换为KB,MB,GB等。 An example output would be a 1024 byte file which is printed as "1KB". 一个示例输出将是一个1024字节的文件,该文件打印为“ 1KB”。 This value is then placed in the listview. 然后将此值放在列表视图中。

What I need to do is sort the size column intelligently. 我需要做的是对大小列进行智能排序。 Right now the sorting is just a simple comparison so 1025 KB is higher than 1024 MB. 现在,排序只是一个简单的比较,因此1025 KB高于1024 MB。 How can I make it "size aware"? 如何使它“知道尺寸”?

My current sorting code is from this KB article: http://support.microsoft.com/kb/319401 And here is my code that generates the file size text: 我当前的排序代码来自此知识库文章: http : //support.microsoft.com/kb/319401这是我的生成文件大小文本的代码:

        public static string getDynamicFileSize(string fileName)
    {
        FileInfo fi = new FileInfo(fileName);
        long sizeInBytes = fi.Length;
        if (sizeInBytes >= 1073741824)
        {
            double sizeInGB = sizeInBytes / Math.Pow(1024, 3);
            return Math.Round(sizeInGB, 2) + " GB";
        }

        if (sizeInBytes >= 1048576)
        {
            double sizeInMB = sizeInBytes / Math.Pow(1024, 2);
            return Math.Round(sizeInMB, 2) + " MB";
        }

        if (sizeInBytes >= 1024)
        {
            double sizeInKB = sizeInBytes / Math.Pow(1024,1);
            return Math.Round(sizeInKB, 2) + " KB";
        }

        //No conversion needed
        return sizeInBytes + " bytes";
    }

Thank you. 谢谢。

Most every object in .NET has a Tag member. .NET中的大多数每个对象都有一个Tag成员。 This is a place where you can stuff anything extra you need to. 在这里,您可以添加任何您需要的东西。 In your case, I would stuff the file size in bytes into the ListViewSubItem.Tag property. 在您的情况下,我会将以字节为单位的文件大小填充到ListViewSubItem.Tag属性中。 Then, your sort algorithm can use that to sort by instead of the column text. 然后,您的排序算法可以使用它代替列文本进行排序。

Possible duplicate of the following answer. 以下答案的可能重复项。 It should solve your problem easily. 它应该可以轻松解决您的问题。

How to sort a listview column that contains file size data? 如何对包含文件大小数据的listview列进行排序? C# C#

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM