Synchronising Sheep (Using LINQ)
Submitted on Apr 14, 2010, 6:11 a.m.
LINQ to Objects in C# has been around for a while now – and yet I’m regularly amazed at how easy LINQ has made it to perform what would have previously been fairly tedious tasks (well unless you were very clever and had written your own set of IEnumerable helper methods) - like the following – where I needed to synchronise a list of records in a database…
/// /// Let's synchronise some sheep.../// public IEnumerable SynchronizeSheep(IEnumerable newSheep, IDbService db){ IEnumerable oldSheep = db.GetSheeps();
foreach (var delete in oldSheep.Except(newSheep)) { db.DeleteSheep(delete.Id); }
foreach (var update in newSheep.Intersect(oldSheep)) { db.UpdateSheep(update); }
foreach (var addition in newSheep.Except(oldSheep)) { db.InsertSheep(addition); }
return db.GetSheeps();}