Cannot convert type IEnumerable to ObservableCollection…are you missing a cast?

笑着哭i 提交于 2019-12-18 09:14:10

问题


I'm trying to return entities where the bool "isAssy" is true:

 public ObservableCollection<MasterPartsList> ParentAssemblyBOM
 {
      get {return this._parentAssemblyBOM.Where(parent => parent.isAssy == true); }
 }

but the entire statement is underlined in red stating that I cannot "convert type IEnumerable to ObservableCollection...are you missing a cast?"


回答1:


ObservableCollection<T> has an overloaded constructor that accepts an IEnumerable<T> as a parameter. Assuming that your Linq statement returns a collection of MasterPartsList items:

public ObservableCollection<MasterPartsList> ParentAssemblyBOM
{
    get 
    {
        var enumerable = this._parentAssemblyBOM
                             .Where(parent => parent.isAssy == true);

        return new ObservableCollection<MasterPartsList>(enumerable); 
    }
}



回答2:


You have to explicitly create the ObservableCollection which at it's most simplest is:

public ObservableCollection<MasterPartsList> ParentAssemblyBOM
{
    get {return new ObservableCollection<MasterPartsList>(this._parentAssemblyBOM.Where(parent => parent.isAssy == true)); }
}

This is potentially inefficient as you are creating new collection every time. However, this might be the simplest solution if you are returning a radically different set of data each time. Otherwise you have to loop through the collection removing items that are no longer in the return set and adding new items.



来源:https://stackoverflow.com/questions/14968948/cannot-convert-type-ienumerable-to-observablecollection-are-you-missing-a-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!