Synchronising Sheep (Using LINQ)

14
Apr
2010

Synchronising Sheep (Using LINQ)

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…

/// <summary>
/// Let's synchronise some sheep...
/// </summary>
/// <param name="newSheep"></param>
/// <param name="db"></param>
/// <returns></returns>
public IEnumerable<Sheep> SynchronizeSheep(IEnumerable<Sheep> newSheep, IDbService db)
{
    IEnumerable<Sheep> 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();
}
Category: