Reputation: 87
I am trying to sort an observable collection of objects by one of their properties in Xamarin Forms.
It seems like the following code should work, but it does not. I am trying to learn as much as I can, so I am very interested why it does not. I'm certain I can copy and paste the solution somewhere, but I've yet to find an answer that explains the why.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
namespace engME
{
public partial class YourFullNamesListPage : ContentPage
{
ObservableCollection<NameObject> _nameList {get; } = MainPage.NameList;
public YourFullNamesListPage()
{
InitializeComponent();
_nameList = _nameList.OrderByDescending(a => a.Name);
FullNamesList.ItemsSource= _nameList;
}
}
}
Upvotes: 0
Views: 4241
Reputation: 16479
Well first of all i don't think your property should be like
ObservableCollection<NameObject> _nameList {get; } = MainPage.NameList;
Since you have to made changes in it later i would suggest you have get as well as set in your property(Since you might have to use it in some other class):
ObservableCollection<NameObject> _nameList {get; set; } = MainPage.NameList;
Then to set your order you do it something like this:
public YourFullNamesListPage()
{
InitializeComponent();
_nameList = new ObservableCollection<NameObject>(_nameList.OrderByDescending(x => x.Name));
FullNamesList.ItemsSource= _nameList;
}
Where the below is of the type System.Linq.IOrderedEnumerable<T>
and hence you need to convert it to an observable collection by wrapping it into one.
_nameList.OrderByDescending(x => x.Name)
And then you are good to go Revert in case of queries.
Upvotes: 1
Reputation: 114
Your _nameList is getonly, thus the following assignment wont change it at all:
_nameList = ObservableCollection<NameObject>(MainPage.NameList.OrderByDescending(a => a.Name));
Upvotes: 0