Sort a list of database fetched from MongoDB

Viewed 115

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?)

2 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();

why not use the ListDatabaseNames method of the client?

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