c# - project one collection into another and keep them in sync -


i have project 1 collection another. easy using select operator linq objects:

var targetcollection = sourcecollection.select(source => new target {     source = source,    //some other stuff here } 

but have keep collections synchronized. when new items added or removed sourcecollection, changes has reflected in targetcollection. have this:

void onsourcecollectionchanged(){    synccollections(sourcecollection, targetcollection) }  void synccollections(icollection<source> sourcecollection, icollection<target> targetcollection) {    //find items no longer present    var newitems = sourcecollection.where(s => !targetcollection.any(t => t.source == s));    //find items added    var olditems = targetcollection.where(t => !sourcecollection.any(s => t.source == s));     foreach(var olditem in olditems)  targetcollection.remove(olditem);     foreach(var source in newitems){        var target = new target{ source = source };        targetcollection.add(target);    } } 

i believe there libraries deal such scenarios. can recommend me some?

i think of api specify projection , maybe 'equality comparer' compare source , target item:

var synchronizer = new collectionsynchronizer<source, target>(     source => new target     {         source = source     });  synchronizer.sync(sourcecollection, targetcollection);  //or specify filter well: synchronizer.sync(     sourcecollection.where(s => s.created > dattime.now.addminutes(-5)),     targetcollection); 

you use observablecollection that:

using system; using system.collections.generic; using system.collections.objectmodel;  public class program {     public static void main()     {         var observablelist = new observablecollection<string>();         var synclist = new list<string>(observablelist);          observablelist.collectionchanged += (o,e) => {              foreach (var item in e.newitems){                 synclist.add((string)item);             }         };          observablelist.add("test");         console.writeline(synclist[0]);     } } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -