按日期排序文件,但按名称排序文件夹

时间:2015-07-09 20:52:36

标签: c# sorting icomparer

试图显示按名称排在顶部的文件夹,然后按日期排序的文件我已经制作了这个PropertyGroupDescription和IComparer

using (ItemCollectionView.DeferRefresh())
{

    var dataView = (ListCollectionView)CollectionViewSource.GetDefaultView(_fileCollection);
    PropertyGroupDescription groupDescription = new PropertyGroupDescription("ObjectType");
    dataView.GroupDescriptions.Add(groupDescription);
    dataView.CustomSort = new StringComparerFiles(false);  
}


public class StringComparerFiles : IComparer 
{

    public StringComparerFiles() : this(false) { }
    public StringComparerFiles(bool descending) { }
    //descending not implemented yet
    public int Compare(object a, object b)
    {
        bool xFolder = false;
        bool yFolder = false;
        string xName = string.Empty;
        string yName = string.Empty;
        DateTime xDate = new DateTime();
        DateTime yDate = new DateTime();


        if (a is FileData)
        {
            xDate = (a as FileData).FileDate; 
        }
        else
        {
            xFolder = true;
            xName = (a as FolderData).FolderName;
        }

        if (b is FileData)
        {
            yDate = (b as FileData).FileDate; 
        }
        else
        {
            yFolder = true;
            yName = (b as FolderData).FolderName;
        }


        if (xFolder && yFolder)
        {
            int n = SafeNativeMethods.StrCmpLogicalW(xName, yName);
            return n;
        }
        else if (xFolder || yFolder) 
            return 0;  //don't compare file and folder
        else
        {
            return DateTime.Compare(xDate, yDate);
        }              
    }
}

结果是我首先列出了文件夹,但只列出了按日期排序的文件夹。我对IComparer的逻辑是否正确?

1 个答案:

答案 0 :(得分:2)

将文件与文件夹进行比较时,不应将它们视为等效文件,但应首先使用该文件夹。