Home > Back-end >  OrderBy property not working - Xamarin Firebase
OrderBy property not working - Xamarin Firebase

Time:04-22

I've seen a few answers here on how to order your Firebase values, but none seem to work on my case.

So, I have the following firebase database: enter image description here

display.xaml.cs:

private void tabelaRestLoad()
{
    var collection = firebaseClient
        .Child("Example")
        .OrderBy("Date")
        .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; }    
}

As you can see, I'm using OrderBy("Date"), and although thats supposedly the right way, it's not returning the data ordered by Date, it is instead returning as default from firebase, sorted by the order it was entered.

I want to add that I wish to order by desc date.

CodePudding user response:

Most likely the library you're using to access Firebase wraps the REST API, which always returns results in an undefined order. From its documentation:

Filtered data is returned unordered: When using the REST API, the filtered results are returned in an undefined order since JSON interpreters don't enforce any ordering. If the order of your data is important you should sort the results in your application after they are returned from Firebase.

So if indeed the library is based on the REST API, OrderBy() is only useful for subsequent filtering in the query. To get the results in a specific order, you'll have to (re)order them in your application code.

CodePudding user response:

  1. Try OrderByChild("Date").

This is because you don't have a Date there, you have the object Item1,Item2 when execute the OrderBy method.

  1. What I suggest is to sort the result database items in view/or before binding DatabaseItems.OrderBy(x => x.Date).

Another option is - change the query and do sorting of the inner array(Item1,Item2...). Try:

private void tabelaRestLoad()
{
    var collection = firebaseClient
        .Child("Example")
        .AsObservable<MyDatabaseRecord>()
        .AsObservableCollection()
        .OrderBy(x => x.Object.Date)
        .Subscribe((dbevent) =>
        {
            if (dbevent != null)
            {
                DatabaseItems.Add(dbevent.Object);
            }
        });
}
  • Related