Reputation: 341
In xamarin forms do I have a Oberservable collection of wordpress posts.
I want to sort this collection by a specific value within this collection?
How am I able to do so in Xamarin forms / c# ?
I can see somewhere are people using:
list.OrderByDescending(x => DateTime.Parse(x)).ToList();
But this does not use a Observable collection or a specific value from this collection to sort.
The fill of my object is this:
FlowObservableCollection<RootObject2> result = JsonConvert.DeserializeObject<FlowObservableCollection<RootObject2>>(await posts.Content.ReadAsStringAsync());
Does anyone have a solution for sorting my array?
My value I wanna sort by is a sub value like: mycollection.group.Myvalue
Thanks in advance!
Upvotes: 1
Views: 1766
Reputation: 4542
I am not familiar with FlowObservableCollection<T>
but from what I could find it seems to be a subtype of ObservableCollection<T>
Microsoft Docs.
Since ObservableCollection<T>
itself is a subtype of Collection<T>
and therefore implements IEnumerable<T>
you should not have any problem using its extension methods, e.g. OrderBy
.
I can see somewhere are people using:
list.OrderByDescending(x => DateTime.Parse(x)).ToList();
My value I wanna sort by is a sub value like: mycollection.group.Myvalue
Are you familiar with lambda expressions as used in the LINQ query of your OrderByDescending()
example?
In case your not, in list.OrderByDescending(x => DateTime.Parse(x)).ToList();
the term x
refers to an element in the list and what your specify to the right of the =>
arrow is your key for ordering.
So if you wanto to order by a different value you could simply write something like myCollection.OrderByDescending(x => x.MyProperty);
Note that you can use terms different from x
as long as they are the same on both sides of the arrow, e.g. myCollection.OrderByDescending(myElement => myElement.MyProperty);
Finally note that the call to myCollection.OrderByDescending()
returns a new IEnumerable
with the elements found in myCollection
and does not change myCollection
itself.
You cannot cast IEnumerable<T>
to FlowObservableCollection<T>
. So if you need an ordered FlowObservableCollection<T>
you have to instantiate a new one using your ordered IEnumerable
as an input.
In your case this is what it might look like:
var orderedElements = myCollection.OrderByDescending(x => x.MyProperty);
var orderedCollection = new FlowObservableCollection<RootObject2>(orderedElements);`
Upvotes: 3
Reputation: 7199
You can try this:
Collection = new ObservableCollection(Collection.OrderBy(x=>x.Date).ToList());
Or adapt this method:
public static void Sort<T>(this ObservableCollection<T> collection, Comparison<T> comparison)
{
var sortableList = new List<T>(collection);
sortableList.Sort(comparison);
for (int i = 0; i < sortableList.Count; i++)
{
collection.Move(collection.IndexOf(sortableList[i]), i);
}
}
Upvotes: 2