如何被用于与mongodb的C#驱动迭代一个IAsyncCursor? [英] How is an IAsyncCursor used for iteration with the mongodb c# driver?

查看:1719
本文介绍了如何被用于与mongodb的C#驱动迭代一个IAsyncCursor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的服务器中的所有数据库的列表,并最终打印出来(即用自己的名字为字符串 S)。与C#驱动程序的previous版本,我可以叫 Server.GetDatabases(),但已被替换 ListDatabasesAsync()

I'm trying to get a list of all the databases in my server and ultimately print them out (i.e. use their names as strings). With the previous version of the c# driver I could call the Server.GetDatabases(), but that has been replaced with ListDatabasesAsync().

返回值是一个 IAsyncCursor<> ,我不知道该怎么办。通过数据库(或其它)这样的光标?

The return value is an IAsyncCursor<> and I'm not sure what to do with it. How does one iterate through the list of databases (or anything) with such a cursor?

推荐答案

简短的回答:使用 ForEachAsync 扩展方法:

var cursor = await client.ListDatabasesAsync();
await cursor.ForeEchAsync(db => Console.Writeline(db["name"]));

龙答:在C#中传统的迭代与的IEnumerable 的foreach 完成。 的foreach 是编译器的语法糖。它实际上是为的GetEnumerator 一个电话,一个使用的范围和,而循环。但是,这并不支持异步操作:

Long answer: Traditional iteration in C# is done with IEnumerable and foreach. foreach is the compiler's syntactic sugar. It's actually a call to GetEnumerator, a using scope and a while loop. But that doesn't support asynchronous operations:

using (var enumerator = enumerable.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var current = enumerator.Current;
        // use current.
    }
}

IAsyncCursor 等同于的IEnumerator IEnumerable.GetEnumerator ),而 IAsyncCursorSource 的IEnumerable 。所不同的是,这些支持异步(并获得了一批每次迭代并不仅仅是一个单一的项目)。不能使用的foreach ,因为它的建成为的IEnumerable ,但你可以全使用实施,而回路的事:

IAsyncCursor is equivalent to IEnumerator (the result of IEnumerable.GetEnumerator) while IAsyncCursorSource is toIEnumerable. The difference is that these support async (and get a batch each iteration and not just a single item). You can't use foreach as it's built for IEnumerable but you can implement the whole using, while loop thing:

IAsyncCursorSource<int> cursorSource = null;

using (var asyncCursor = await cursorSource.ToCursorAsync())
{
    while (await asyncCursor.MoveNextAsync())
    {
        foreach (var current in asyncCursor.Current)
        {
            // use current
        }
    }
}

然而,这是一个很大的样板,从而使司机增加了像 ForEachAsync ,<$ C $为 IAsyncCursor 的扩展方法C> ToListAsync 等等。

However that's a lot of boilerplate so the driver adds extension methods for IAsyncCursor like ForEachAsync, ToListAsync and so forth.

这涵盖了最常见的用例,但对别人你仍然需要自己实现迭代。

That covers most common use cases but for others you do still need to implement the iteration yourself.

这篇关于如何被用于与mongodb的C#驱动迭代一个IAsyncCursor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆