Question

I have a ObservableCollection property that I need to manipulate with LINQ.

What I want to do is take the first collection and remove items from another collection, based on the item's property.

This is what I have so far:

ItemsObservableCollection = ItemsObservableCollection.Where(i=>!selectedItemsObservableCollection.Any(y=> y.name == i.Name);

If I do it this way, I get a casting error that says I cannot cast an IEnumerable to a ObservableCollection. If I save the value into a var, it does exactly what I want:

    var collectionItems= ItemsObservableCollection.Where(i=>!selectedItemsObservableCollection.Any(y=> y.name == i.Name);

but I need it to update the ObservableCollection property.

Was it helpful?

Solution 2

Instead of creating a new collection, you could just remove the items you want from the original. This is preferable if, for example, you're working in WPF and have bound the observable collection to a control.

var itemsToRemove = ItemsObservableCollection.Where(
    i => !selectedItemsObservableCollection.Any(y => y.name == i.Name)).ToList();

foreach (var item in itemsToRemove)
    ItemsObservableCollection.Remove(item);

(Have to use ToList() to avoid a "collection was modified" error.)

OTHER TIPS

Well, you've got an ObservableCollection ctor which takes an IEnumerable<T>

so you may do

ItemsObservablecollection = new ObservableCollection<DesiredType>(ItemsObservableCollection.Where(i=>!selectedItemsObservableCollection.Any(y=> y.name == i.Name));

You need my ObservableComputations library. That is .NET API for computations over INotifyPropertyChanged and INotifyCollectionChanged (ObservableCollection) objects. Results of the computations are INotifyPropertyChanged and INotifyColectionChanged (ObservableCollection) objects.

Using this library you can code like this:

var collectionItems= ItemsObservableCollection.Filtering(i=> 
    !selectedItemsObservableCollection.AnyComputing(y => y.name == i.Name).Value);

collectionItems is ObservableCollection and reflects all the changes in the ItemsObservableCollection collection and Name properties. Ensure that all properties mentioned in the code above notify of changes through the INotifyPropertyChanged interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top