我有一个要与 OrderBy 一起使用的自定义比较器。这个比较器可以按照我想要的方式对嵌套列表进行排序。我在其他地方完美地工作,但我不能让它以我想要的方式与 Linq 一起工作。你能告诉我哪里错了吗?
编辑:我想让它工作的方式是首先按类(BaseDirectory > BaseSite > VideoEntity,总是)对我的实体进行分组,然后按字母顺序对它们进行排序(升序 = A-> Z,或降序 Z-> A)。无论如何,当我使用 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;
}