IComparer,OrderBy和Linq

时间:2012-07-27 08:00:46

标签: c# linq sql-order-by icomparer

我有一个自定义比较器,我想与OrderBy一起使用。此比较器可以按我想要的方式对嵌套列表进行排序。我完全在其他地方工作,但我无法按照Linq的方式工作。你能告诉我我哪里错了吗?

编辑:我想让它工作的方式是首先按类分组我的实体(BaseDirectory> BaseSite> VideoEntity,总是),然后按字母顺序对它们进行排序(升序= A-> Z,或降序Z- >一种)。无论如何,当我使用SortDirectoriesDescending()时,我返回按升序排序的集合。 默认情况下,集合按升序模式排序(因此转换器可以正常工作,我已经测试它是否可以降序,也可以正常)

public class VideoEntityComparer : IComparer<VideoEntity>
{

    int order = 1;

    public VideoEntityComparer(Boolean ascending)
    {
        if (!ascending)
        {
            this.order = -1; // so descending
        }
    }

    public VideoEntityComparer()
    {

    }

    public int Compare(VideoEntity x, VideoEntity y)
    {
        if ((x is BaseDirectory && y is BaseDirectory) || (x is BaseSite && y is BaseSite) || (x is VideoEncoder && y is VideoEncoder))
        {
            return string.Compare(x.Nom, y.Nom, false) * order; // only objects of the same type are sorted alphabetically
        }
        else if ((x is BaseDirectory && y is BaseSite) || (x is BaseSite && y is VideoEncoder))
        {
            return -1;
        }else
        {
            return 1;
        }
    }
}

private void SortDirectoriesDescending(object sender, RoutedEventArgs e)
    {
        ObservableCollection<BaseDirectory> tempDir  = new ObservableCollection<BaseDirectory>(
            Directories.OrderBy(directory => directory, new VideoEntityComparer(false)));
        Directories = tempDir;
    }

1 个答案:

答案 0 :(得分:1)

尝试对比较方法进行以下更改:

public int Compare(VideoEntity x, VideoEntity y)
{
    if ((x is BaseDirectory && y is BaseDirectory) || (x is BaseSite && y is BaseSite) || (x is VideoEncoder && y is VideoEncoder))
    {
        return string.Compare(x.Nom, y.Nom, false) * order; // only objects of the same type are sorted alphabetically
    }
    else if ((x is BaseDirectory && y is BaseSite) || (x is BaseSite && y is VideoEncoder) || (x is BaseDirectory && y is VideoEncoder)) // Added (x is BaseDirectory && y is VideoEncoder)
    {
        return -1;
    }
    else
    {
        return 1;
    }
}

您之前的代码是定义订单BaseDirectory&lt; BaseSite和BaseSite&lt; VideoEncoder,但BaseDirectory &gt; VideoEncoder,由于您的订购不具有传递性,因此似乎可能会混淆OrderBy