如何从Azure DocumentDB查询结果中选择第一个元素

3

我对C#编程相对较新,需要一些帮助。

我的DocumentDB查询返回一个类型为{System.Collections.Generic.List<object>}的对象,其计数为1。是否有方法可以只选择索引为0的元素,而无需迭代变量?

以下是查询字符串的样式

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

我想提醒您,这里没有使用实体,数据是动态的,因此没有映射到对象。


你好,现在有进展了吗? - Jay Gong
1个回答

3

1. 您可以使用 SQL 查询语句:SELECT top 1 * FROM c

enter image description here

2. 您可以在 SDK 中使用 FirstOrDefault() 方法。

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.你可以按照@Sajeetharan所说的,在FeedOptions参数中设置MaxItemCount = 1。

希望它能帮助你。


以上的选项2会从数据库中检索超过1个对象吗?(我的意思是在选择第一个对象之前..像选择top 1 xxx而不是选择*,然后只使用第一个对象) - user230910
@user230910 不,你可以测试它。 - Jay Gong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接