To be more specific, let’s say we have a collection sorted by properties P1 and P2 like this:
- A 1
- A 2
- A 2
- A 3
- B 1
- B 1
- B 2
- B 3
When doing a foreach through the collection, I want to get notified whenever a property changes.
So for P1 I need the following 4 notifications in this particular order:
- OnBeforeGroup(P1, “A”)
- OnAfterGroup(P1, “A”)
- OnBeforeGroup(P1, “B”)
- OnAfterGroup(P1, “B”)
For P2 this would make 12 notifications, spare me the list.
Of course, I can do this in every use case by saving the “old” property values within the foreach loop (OldP1 = P1) and firing an event/executing a method when P1 != OldP1, but that’s not reusable.
Is there a collection that already implements this pattern?
If not, any advice how to make it more reusable?
Edit: Note, I just want to get notified during foreach loop if some property value is different than it was in previous iteration, this has nothing to do with INotifyPropertyChanged etc.
.NET has
ObservableCollection<T>but that’s used to watch changes happening to objects stored and collection itself. Your collection isn’t changing (given I understood you correctly) – you just want to get notified during loop if some property value is different than it was in previous iteration.Something that might point you in the right direction, in terms of having reusable code:
And, assuming we’re dealing with
P1andP2properties you mentioned, usage would look like this:This is by no means complete solution. It should work when simple values are concerned (so
.Equalscan handle comparing easily). Of course, you still need to add some event toPropertyWatcherclass and perhaps tweak it here and there – but I think general idea is fairly easy to grasp.For more advanced scenarios though, I suppose you’ll have to work o more generic approach.