I have an ObservableCollection
that is filled with custom elements of type Video runtime. These have the properties of Name, Rating and Number of Viewers.
I want to display the Video elements in different orders based on whichever of the three criteria the user chooses during Application Runtime. I created the following Enum
to store the possible choices:
public enum OrderBy
{
[Description("Video Name")]
Name = 0,
[Description("Video Rating")]
Rating = 1,
[Description("Number of Viewers")]
ViewerNumber = 2
}
These are fed into a ComboBox
called OrderCombo allowing the user to change the order criteria (I'm displaying the Description
to the user):
foreach (var item in Enum.GetValues(typeof(OrderBy)))
{
OrderCombo.Items.Add(((OrderBy)item).GetDescription());
}
To avoid sorting, I used LINQ to get the order and I came up with the following:
IOrderedEnumerable<Video> GetOrder()
{
switch (OrderCombo.SelectedIndex)
{
case 0:
return videos.OrderBy(x => x.Name);
case 1:
return videos.OrderByDescending(x => x.Rating);
case 2:
return videos.OrderByDescending(x => x.NumberOfViewers);
}
return videos.OrderBy(x => x.Name);
}
Then, I call this function every time a new element is added or an element is delelted or the user changes the order:
VideoUIElment.ItemsSource = GetOrder();
So basically I keep re-calculating the enumerable every time, which workswpf but I'm wondering if there is a more efficient/elegant way of doing this.
Maybe store the order in one or several Func<>
s? I tried them, but they can only be of a (compile-time) fixed type as in Func<Video, string>
for Name and I would rather avoid using implementations like Func<Video, dynamic>
.