Alan Alan - 4 months ago 12
C# Question

How can I compare two C# collections and issue Add, Delete commands to make them equal?

I have two ICollection collections:

public partial class ObjectiveDetail
{
public int ObjectiveDetailId { get; set; }
public int Number { get; set; }
public string Text { get; set; }
}

var _objDetail1: // contains a list of ObjectiveDetails from my database.
var _objDetail2: // contains a list of ObjectiveDetails from web front end.


How can I iterate through these and issue and Add, Delete or Update to synchronize the database with the latest from the web front end?

If there is a record present in the first list but not the second then I would like to:

_uow.ObjectiveDetails.Delete(_objectiveDetail);


If there is a record present in the second list but not the first then I would like to:

_uow.ObjectiveDetails.Add(_objectiveDetail);


If there is a record (same ObjectiveDetailId) in the first and second then I need to see if they are the same and if not issue an:

_uow.ObjectiveDetails.Update(_objectiveDetail);


I was thinking to do this with some kind of:

foreach (var _objectiveDetail in _objectiveDetails) {}


but then I think I might need to have two of these and I am also wondering if there is a better way. Does anyone have any suggestions as to how I could do this?

Answer

The following code is one of some possible solutions

var toBeUpdated =
            objectiveDetail1.Where(
            a => objectiveDetail2.Any(
                b => (b.ObjectiveDetailId == a.ObjectiveDetailId) && 
                     (b.Number != a.Number || !b.Text.Equals(a.Text))));

var toBeAdded =
            objectiveDetail1.Where(a => objectiveDetail2.All(
            b => b.ObjectiveDetailId != a.ObjectiveDetailId));

var toBeDeleted =
            objectiveDetail2.Where(a => objectiveDetail1.All(
            b => b.ObjectiveDetailId != a.ObjectiveDetailId));

The rest is a simple code to Add, Delete, Update the three collections to the database.

Comments