对从 MongoDB 中获取的数据库列表进行排序

Sort a list of database fetched from MongoDB

尝试编码

Client = new MongoClient($"mongodb://{connectionParameters}");

List<dynamic> names = Client.ListDatabases().ToList()
      .Select(x => new { name = x["name"].ToString() })
      .OrderBy(x => x.name)
      ;

但编译器显示错误

Cannot implicitly convert type
'System.Linq.IOrderedEnumerable<>'
to
'System.Collections.Generic.List'.

An explicit conversion exists (are you missing a cast?)

不确定补救措施是什么。

也试过

List<string> names = Client.ListDatabases().ToList()
    .Select(x => x["name"].ToString())
    ;

但也有误

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

如果您查看 OrderBy 的文档,您会发现它 returns:

IOrderedEnumerable<TSource>

但您希望它是 List,因此您只需要在最后调用 ToList()

List<dynamic> names = Client.ListDatabases().ToList()
      .Select(x => new { name = x["name"].ToString() })
      .OrderBy(x => x.name)
      .ToList();

为什么不用客户端的ListDatabaseNames方法?

var dbNames = client.ListDatabaseNames()
                    .ToList()
                    .OrderBy(n => n)
                    .ToArray();