[英]IComparer, OrderBy and Linq
I have a custom comparer I want to use with OrderBy. 我有一个要与OrderBy一起使用的自定义比较器。 This comparer enables to sort nested lists the way I want.
此比较器使我可以按所需的方式对嵌套列表进行排序。 I perfectly works somewhere else, but I can't make it work the way I want with Linq.
我可以在其他地方完美地工作,但是我无法使其与Linq一起工作。 Can you tell me where I'm wrong?
你能告诉我我错了吗?
EDIT : the way I want to make it work is to group my entities first by class (BaseDirectory > BaseSite > VideoEntity, always), then sort them alphabetically (ascending = A->Z, or descending Z->A). 编辑:我要使其工作的方法是先按类对我的实体进行分组(始终是BaseDirectory> BaseSite> VideoEntity),然后按字母顺序对它们进行排序(升序= A-> Z或降序Z-> A)。 Anyway when I use SortDirectoriesDescending(), I'm returned the collection sorted in ascending.
无论如何,当我使用SortDirectoriesDescending()时,我都会返回以升序排序的集合。 By default the collection is sorted in ascending mode (so the converter works, and I've tested it for descending, OK too)
默认情况下,集合按升序排序(因此转换器可以工作,我已经对其进行了降序测试,也可以)
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;
}
Try making the following change to your compare method: 尝试对您的compare方法进行以下更改:
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;
}
}
Your code previously was defining an order BaseDirectory < BaseSite, and BaseSite < VideoEncoder, but BaseDirectory > VideoEncoder, which seems likely to confuse OrderBy
since your ordering is not transitive. 您的代码以前定义的订单是BaseDirectory <BaseSite和BaseSite <VideoEncoder,但是BaseDirectory > VideoEncoder似乎很容易混淆
OrderBy
因为您的订购不具有传递性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.