【问题标题】:Convert IMongoCollection to ObservableCollection将 IMongoCollection 转换为 ObservableCollection
【发布时间】:2020-08-08 07:31:15
【问题描述】:

无法将IMongoCollection<MatchDocument> 转换为ObservableCollection<MatchDocument>

MongoClient client = new MongoClient();
var DB = client.GetDatabase("MTR");
var Collection = DB.GetCollection<MatchDocument>("MATCHES");
App.Profiles = new ObservableCollection<MatchDocument>(Collection);

【问题讨论】:

  • 您遇到错误了吗?如果是这样,你为什么不告诉我们错误是什么? ObservableCollection 构造函数接受 IEnumerable 或 List,IMongoCollection 是其中之一吗?
  • 我的解决方案对您有用吗?如果是,请您接受(点击此答案左上角的☑️),以便我们可以帮助更多有相同问题的人:)。

标签: c# mongodb xamarin.forms type-conversion observablecollection


【解决方案1】:

你可以使用Collection.Find&lt;MatchDocument&gt;(query).ToListAsync():

    MongoClient client = new MongoClient();
    var DB = client.GetDatabase("MTR");
    var Collection = DB.GetCollection<MatchDocument>("MATCHES");

    Task<IList<MatchDocument>> doc = await Collection.Find<MatchDocument>(query).ToListAsync();

    ObservableCollection<MatchDocument> Profiles = new ObservableCollection<MatchDocument>(doc.Result);

参考:cannot convert from 'MongoDB.Driver.IMongoCollection<>' to 'System.Collections.Generic.IEnumerable<>'

【讨论】:

  • 任务> doc = await Collection.Find(query).ToListAsync(); //不能将类型'System.Collections.Generic.List'隐式转换为'System.Threading.Tasks.Task>'
  • 您在运行时收到此错误?对我来说效果很好。
  • 是的,我遇到了异常。
  • 你能分享我一个最小的、可重现的例子吗?我无法重现我这边的问题。
猜你喜欢
  • 2014-11-05
  • 1970-01-01
  • 2013-09-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多