Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select first element from Azure DocumentDB Query result

I am relatively new to C# programming and would like some assistance.

My Query from DocumentDB returns an object of the following type {System.Collections.Generic.List<object>} which has a count of 1. Is there a way I could just select the element at index zero without iterating over the variable?

Here is how the query string looks

return _dbclient.CreateDocumentQuery<dynamic>(dblink,"select * from c " + sb.ToString()).ToList();

I am not using entities FYI, the data is dynamic and therefore not mapped to objects

like image 241
Masinde Muliro Avatar asked Nov 28 '25 19:11

Masinde Muliro


1 Answers

1.You could just sql : SELECT top 1 * FROM c

enter image description here

2.You could use FirstOrDefault() in sdk.

private static readonly string endpointUrl = "https://***.documents.azure.com:443/";
private static readonly string authorizationKey = "***";
private static readonly string databaseId = "db";
private static readonly string collectionId = "item";
private static DocumentClient client;

public static async void QueryTest()

        {
            client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
            var uri = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
            Item queryItem = client.CreateDocumentQuery<Item>(uri , "select * from c")
                                            .AsEnumerable()
                                            .FirstOrDefault();

            Console.WriteLine("\nRead {0}", queryItem);
       }
}

enter image description here

3.You could set MaxItemCount =1 in FeedOptions parameter as @Sajeetharan said.

Hope it helps you.

like image 159
Jay Gong Avatar answered Dec 01 '25 08:12

Jay Gong