I have an ObservableCollection<Data> Items
Data has a “Columns” property on it which is again an ObservableCollection<Column>.
A Column object has a boolean property called “IsActive”.
I have a case where I need to determine if all “Items” have the “Columns” property and if so,
all the columns should either have “IsActive” as true or false but not both.
The trick is i need to put this logic in CanExecute of a button.. I will need to make this as efficient and fast as possible…Any ideas?
The struture is:
public class MyClass
{
public ObservableCollection<Data> Items
{
get{return _items;}
}
}
public class Data
{
public ObservableCollection<Column> Columns
{
get{return _columns;}
}
}
public class Column
{
public bool IsActive{ get; set;}
}
Thanks!
This smells like premature optimization. Have you measured the speed of a simplistic approach? Iterating through a few not too big collections will only take a few milliseconds on a modern CPU.
If you want to use LINQ to compute if all
Columnobjects are either active or inactive you can use this expression.This code will iterate over all elements in all collections. You can improve on this by using a
forloop and breaking it when both boolean variables becomes false. This can also by done in LINQ usingTakeWhileusing a predicate with side effects but a simpleforloop is probably easier to understand.If you decide that a simplistic approach is too slow you need to keep track of the
CanExecuteproperty at theMyClasslevel. You can do this by setting up change notification handlers for all theObservableCollectioninstances. It is somewhat tedious because you have two levels of collections but it will ensure that whenever aColumnis added or removed from a collection or theIsActiveproperty is changed the boolean variable backingCanExecuteinMyClassis updated.Initially
Columnhas to implementINotifyPropertyChanged:Datahas to expose the desired property which for lack of better name I have calledAllColumnsAreActiveOrInactiveand changes to this property is signaled by implementingINotifyPropertyChanged.To track the status of all columns the
CollectionChangedof theColumncollection is handled. When a newColumnis added the value ofAllColumnsAreActiveOrInactivecan be recomputed without iterating theColumncollection. However, whenIsActivechanges on a singleColumnor when aColumnis removed the collection has to be iterated to determine the new value of theAllColumnsAreActiveOrInactive.To complete this solution the
Column/Datacollection approach has to be repeated for theData/MyClasscollection.