I have a custom comparer I want to use with 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. 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). Anyway when I use SortDirectoriesDescending(), I'm returned the collection sorted in ascending. 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;
}
OrderBy
method? The call toOrderBy
looks correct. – Adam Houldsworth