I want to order alphabetically an ObservableCollection because I don't wanna have to create another binding. I've seen we could use Linq and the method OrderBy. I would like also to use a personal IComparer because I will have to organize complex datas (lists into other lists), but VS tells me I can't use my own comparer :
(give you the link of the error because my VS is in french)
http://msdn.microsoft.com/en-gb/library/hxfhx4sy%28v=vs.90%29.aspx
Any ideas ?
private void SortGraphicObjectsAscending(object sender, RoutedEventArgs e)
{
GraphicObjects.OrderBy(graphicObject => graphicObject.Nom, new GraphicObjectComparer(true));
}
And my own comparer (which is already tested)
public class GraphicObjectComparer : IComparer<GraphicObject>
{
int order = 1;
public GraphicObjectComparer(Boolean ascending)
{
if (!ascending)
{
order = -1;
}
}
public GraphicObjectComparer()
{
}
public int Compare(GraphicObject x, GraphicObject y)
{
return String.Compare(x.Nom, y.Nom, false) * order;
}
}
Thanks for your answers. Anyway I have another problem. As Michael said, I use a more complex comparer but for another entity. This entity is displayed with a hierarchical tree, and an object might contain a list of other objects of the same type.
I couldn't test an my GraphicObject becuse I don't have access to the DB (there was no object at the moment). With the tests on my VideoEntity it seems my ObservableCollection is not sorted the way I want (I create another one). I want to reverse it alphabetically but it doesn't work.
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;
}
PS : by the way, I'm acting on a DependancyProperty. Is it the correct way to do it ? (I'm new on WPF)