Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of database fetched from MongoDB

Tried coding

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

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

but the compiler shows error

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

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

Not sure what the remedy is.

Also tried

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

but also errored

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

like image 403
Richard Avatar asked Aug 31 '25 23:08

Richard


1 Answers

If you look at the documentation of OrderBy you'll see that it returns:

IOrderedEnumerable<TSource>

but you expect it to be a List, so you simply need a last call of ToList() at the end

List<dynamic> names = Client.ListDatabases().ToList()
      .Select(x => new { name = x["name"].ToString() })
      .OrderBy(x => x.name)
      .ToList();
like image 64
Mong Zhu Avatar answered Sep 03 '25 12:09

Mong Zhu