'Sort ObservableCollection with data from Firebase - Xamarin Firebase

I display my data from a Firebase database to a Xamarin app.

My data on the database is structured like this:enter image description here

And my code to call that data is the following:

display.xaml.cs:

    private void tableLoad()
{
    var collection = firebaseClient
        .Child("Example")
        .AsObservable<MyDatabaseRecord>()
        .Subscribe((dbevent) =>
        {
            if (dbevent != null)
            {
                DatabaseItems.Add(dbevent.Object);
            }
        });
}

display.xaml:

<StackLayout>
    <CollectionView ItemsSource="{Binding DatabaseItems}" SelectionMode="Single">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                            <Label Text="{Binding Name}" />
                            <Label Text="{Binding Date}"/>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

myDatabaseRecord.cs:

public class MyDatabaseRecord
{
    public string Name { get; set; }
    public string Date { get; set; }    
}

What can I change to my "Display.xaml.cs" to sort the data I retrieve from firebase? I tried adding something like this:

private void tableLoad()
    {
        var collection = firebaseClient
            .Child("Example")
            .AsObservable<MyDatabaseRecord>()
            .Subscribe((dbevent) =>
            {
                if (dbevent != null)
                {
                    DatabaseItems.Add(dbevent.Object);
                }
            });
    DatabaseItems = new ObservableCollection<MyDatabaseRecord>(DatabaseItems.OrderBy(i => i.Date));
    }

But when I run the app it doesn't return any item from the database



Solution 1:[1]

As Jason commented, the way you currently store the data doesn't make it easy to sort on. If you want to store the date as a string, store it in ISO 8859-1 format, which does allow sorting:

"2022-04-05"

Once you use this format for your Date properties, you can use Firebase's built-in ordering operator to get the child nodes in date order:

firebaseClient
    .Child("Example")
    .OrderByChild("Date")
    .AsObservable<MyDatabaseRecord>()
    .Subscribe((dbevent) =>
        ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen