将IEnumerable转换为自定义ObservableCollection类?

时间:2015-08-28 03:37:31

标签: c# inheritance casting

是否可以将IEnumerable转换为从ObservableCollection类进入的自定义类?

原因是我想在获取上仅选择一组已过滤的项目。我想在获取上实现它,因为许多其他属性引用 CustomItems 并对项目执行处理,但我想以某种方式使其处理过滤的项目集取决于是否是否启用了值。

下面是帮助解释我想要实现的内容的代码:

public class CustomItemsCollection : ObservableCollection<ItemViewModel>
{
    public ListView ListView { get; set; }
    public void ScrollToItem(object item = null)
    {
        //Some custom Code
    }
}

这是我想要自定义的属性:

private CustomItemsCollection _CustomItems = null;
    [JsonProperty]
    public CustomItemsCollection CustomItems
    {
        get
        {
            if (_CustomItems != null)
            {
                if(SomeValueIsEnabled)
                {
                    var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue));
                    var castedItems = (CustomItemsCollection)filteredItems;
                    return castedItems;
                }
                return _CustomItems;
            }

            _CustomItems = new CustomItemsCollection();
            _CustomItemsChangedSource = new CollectionChangedWeakEventSource();
            _CustomItemsChangedSource.SetEventSource(_CustomItems);
            _CustomItemsChangedSource.CollectionChanged += _CustomItemsChangedSource_CollectionChanged;
            return _CustomItems;
        }
        set { _CustomItems = value; RaisePropertyChanged("CustomItems"); }
    }

具体来说,这部分:

if(SomeValueIsEnabled)
{
    var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue));
    var castedItems = (CustomItemsCollection)filteredItems;
    return castedItems;
}

这可能/或者可能是错的吗?这样做的最佳做法是什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

您不能投射它,但您可以创建CustomItemsCollection的实例并使用filteredItems对其进行初始化。

将构造函数添加到自定义类,并传递给appropriate ObservableCollection constructor

public class CustomItemsCollection : ObservableCollection<ItemViewModel>
{
    public CustomItemsCollection(IEnumerable<ItemViewModel> items)
        : base(items) { }

   // your other code here
}

然后你可以这样做:

var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue));
var collection = new CustomItemsCollection(filteredItems);
return collection;

答案 1 :(得分:0)

尝试使用此代码:

 var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue))
.Select(pre=> new ItemViewModel(){
//add info here
});
var castedItems = new CustomItemsCollection(filteredItems);