TobiasBuchholz / Plugin.Firebase

Wrapper around the native Android and iOS Firebase Xamarin SDKs
MIT License
211 stars 49 forks source link

Coverting from IDocumentSnapshot<T> to a List<T> #256

Closed rezamohamed closed 6 months ago

rezamohamed commented 8 months ago

This is more a usage question Plugin.Firebase.Firestore.

I can retreieve an IEnumberable<IDocumentSnapshot> using

        var snapshot = await CrossFirebaseFirestore
            .Current
            .GetCollection("NewCollection")
            .GetDocumentsAsync<Pokemon>();

        var docs = snapshot.Documents;

But to create a List is the only way to iterate through snapshot.documents like so?

        List<Pokemon> allData = new List<Pokemon>();

        foreach (var doc in snapshot.Documents)
        {
            allData.Add(doc.Data);
        }

I've used this plugin in Xamarin before, https://github.com/f-miyu/Plugin.CloudFirestore/tree/master?tab=readme-ov-file#get and it does a direct ToObject, so didn't know if I was missing something here is all.

AdamEssenmacher commented 8 months ago

The Documents property is an IEnumerable<T> for good reason. It defers the work needed to translate underlying native data objects to cross-platform .NET objects.

You can use the standard .NET extension method .ToList() to transform the IEnumerable<T> into a List<T>. This is functionally equivalent to the code you've posted but more terse.

rezamohamed commented 8 months ago

My issue isn't with the IEnumerable, performing a ToList like so simply gives me a List instead of the IEnumberable.

var docs = snapshot.Documents.ToList();

My question was that I still have a List<IDocumentSnapshot>, I am looking to get the List<Pokemon>without having to iterate through and add each Pokemon to the list.

With the code that I was comparing to from the other plugin, yourmodels is aList<Pokemon>

var document = await CrossCloudFirestore.Current
                                        .Instance
                                        .Collection("yourcollection")
                                        .Document("yourdocument")
                                        .GetAsync();

var yourModel = document.ToObject<YourModel>();
AdamEssenmacher commented 8 months ago

Ah sorry. I understand now. The ToObjects() and ToObject() methods in the other plugin are just convenience methods for iterating over each snapshot just like you're doing. This plugin doesn't have equivalents right now, so yes you'll need to iterate yourself like: snapshot.Documents.Select(d => d.Data). It would be an easy enough thing to add, or create an extension method for.

rezamohamed commented 8 months ago

Thanks @AdamEssenmacher that was my hunch, but i wanted to just make sure. The sample project here doesn't have a sample for firestore, so wanted to make sure I wasn't missing something