C# Dictionary change notification (INotifyCollectionChanged) -
i have loop running retrieving live share prices. want check if of prices retrieved different price have stored in dictionary , notify me details of have changed. looking along lines of dictionary utilising inotifycollectionchanged.
e.g.
using system; using system.collections.generic; using system.collections.specialized; using system.linq; namespace basicexamples { class collectionnotify:inotifycollectionchanged { public dictionary<string, string> notifydictionary{ get; set; } public collectionnotify() { notifydictionary = new dictionary<string, string>(); } public event notifycollectionchangedeventhandler collectionchanged; protected virtual void oncollectionchanged(notifycollectionchangedeventargs e) { if (collectionchanged != null) { collectionchanged(this, e); } } public void add(object k, object v) { notifydictionary.add(k.tostring(),v.tostring()); oncollectionchanged(new notifycollectionchangedeventargs(notifycollectionchangedaction.add,0)); } public void update(object k, object v) { bool isupdated = false; ilist<string> changeditems = new list<string>(); int index; if (notifydictionary.containskey(k.tostring())) { notifydictionary[k.tostring()] = v.tostring(); changeditems.add(k+":"+v); isupdated = true; } else { add(k, v); } if (isupdated) { oncollectionchanged(new notifycollectionchangedeventargs(notifycollectionchangedaction.replace,changeditems,changeditems)); } } } }
with main program calling add/update test. when looping through notifycollectionchangedeventargs have nest loop , cast ienumerable - seems long winded way round.
using system; using system.collections; using system.collections.generic; using system.collections.specialized; using system.linq; using system.text; using system.threading.tasks; namespace basicexamples { class program { //delegate static void main(string[] args) { //notify collection collectionnotify notify = new collectionnotify(); notify.collectionchanged += collectionhaschanged; notify.add("test1", "test2"); notify.add("test2","test2"); notify.add("test3", "test3"); notify.update("test2", "test1"); notify.update("test2", "test3"); notify.update("test3", "test1"); notify.update("test1", "test3"); #region lamba //lamba list<int> mylist = new list<int>() {1,1,2,3,4,5,6}; list<int> newlist = mylist.findall(s => { if (s == 1) { return true; } return false; }); foreach (int b in newlist) { console.writeline(b.tostring()); } #endregion } public static void collectionhaschanged(object sender, eventargs e) { notifycollectionchangedeventargs args = (notifycollectionchangedeventargs) e; if (args.action == notifycollectionchangedaction.replace) { foreach (var item in args.newitems) { foreach (var nextitem in (ienumerable)item) { console.writeline(nextitem); } } } } } }
i suppose question 2 fold:- a: best way use notifiable dictionary? b: should use nested loop above retrieve updated values?
thanks in advance
Comments
Post a Comment