Using .Select() vs using foreach on a collection

I was trying to update View by changing the collection on my ViewModel. My ViewModel has an observable collection that was bound to an items control on the View. I wanted to change values of some of the objects in my ViewModel collection. What i found is that if you do a .select(), it returns you a copy of the selected subset items so making any changes to that copy doesn’t really affect the binding. If i do the traditional foreach, then changing any element in the collection, correctly updates the UI.

So for beginners in MVVM design pattern using WPF, here is what i mean:

I have a list in my viewmodel.

public List<Emp> employees{get;set;} Each employee has a boolean field called isActive.

This list is bound to an items control on View and the isActive is bound to checkbox(checkbox is part of the datatemplate which is defined for the itemscontrol’s ¬†itemtemplate). Now if i want to say reset the View and untick all the boxes, i need to do a foreach loop and set individual employee isActive field to false to reflect it correctly on View via DataBinding(i am assuming you have got NotifyPropertyChange() in place)

But if you do select i.e. => emp.isActive == true), this will return you all the active employees and now if you updated all this employees to isActive = false, View remains unchanged.

So select is intended only for selecting items for readonly purposes. if you want to make changes, we need to go back to the original collection which is by using foreach loop.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s