【问题标题】:Sort a list of database fetched from MongoDB对从 MongoDB 获取的数据库列表进行排序
【发布时间】:2019-06-24 14:50:20
【问题描述】:

尝试编码

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

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

但编译器显示错误

无法隐式转换类型
'System.Linq.IOrderedEnumerable'

'System.Collections.Generic.List'。

存在显式转换(您是否缺少强制转换?)

不确定补救措施是什么。

也试过了

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

但也出错了

无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少演员表?)

【问题讨论】:

    标签: .net mongodb linq c#-2.0


    【解决方案1】:

    如果您查看 OrderBy 的文档,您会看到它返回:

    IOrderedEnumerable&lt;TSource&gt;

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我猜是因为我看到了一个例子,或者找到了 ListDatabases first 的文档 :)
      猜你喜欢
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      相关资源
      最近更新 更多