Sens4
Sens4

Reputation: 665

Query ObservableCollection with Linq MVVM

I want to create a query with linq on my ObservableCollection but it doesn't really work how T tried it.

I have a Model Entry which has {note, information, isActive} as parameters. So I now want to simply just get all the Entries where isActive is true. I don't use it on my dataprovider (once the data gets loaded) because I need to load every entry into the program.

So I thought about to override the getter inside my entries ObservableCollection:

    public ObservableCollection<Note> _entries { get; set; }
    public ObservableCollection<Note> entries
    {
        get
        {
            return new ObservableCollection<Note>(from entry in this._entries
                                                  where entry.isActive == true
                                                  select entry);
        }
        set { this._entries = value; }
    }

But as you might guess this doesn't work.

Regards

Upvotes: 1

Views: 2062

Answers (2)

Felix Castor
Felix Castor

Reputation: 1675

Rather than editing it in the get, try updating the refinedEntries in the entries' setter. My Linq statement may need work but it encapsulates what I'm trying to suggest.

Essentially keep a copy of everything even the inactive records in entries and another collection to contain only the active records. In this case I'm calling it refinedEntries.

    private ObservableCollection<Note> _entries;

    public ObservableCollection<Note> entries
    {
      get{return _entries;}
      set
      {
        _entries = value;
        RefinedEntries = new ObservableCollection(_entries.Where(e=>e.isActive).Select(e => e));
      }

     }

    public ObservableCollection<Note> refinedEntries {get;set;}

I would also suggest updating refinedEntries when CollectionChangedEvent fires. In this case the only time refinedEntries is updated is when entries is set to a new instance.

When you instantiate an new collection for entries, subscribe to its CollectionChangedEvent. For example if you instantiate the collection in the Model's constructor you could use the following..

entries = new ObservableCollection<Note>();
entries.CollectionChangedEvent += new NotifyCollectionChangedEventHandler((sender,args) => 
{ 
   RefinedEntries = new ObservableCollection(_entries.Where(e=>e.isActive).Select(e => e));
  //Notify the UI that an update has been made.
  OnPropertyChanged("RefinedEntries");
});

Upvotes: 1

auburg
auburg

Reputation: 1475

Try

        get
        {
            List<Notes> list = _entries.Where(e=>e.isActive).ToList(); 
            return new ObservableCollection<Note>(list) ;
        }

Upvotes: 3

Related Questions