Compare two lists of object for new, changed, updated on a specific property

前端 未结 4 2116
时光取名叫无心
时光取名叫无心 2020-12-15 06:06

I\'ve been trying and failing for a while to find a solution to compare to lists of objects based on a property of the objects. I\'ve read other similar solutions but they w

4条回答
  •  余生分开走
    2020-12-15 06:16

    One simple approach would be to override the == operator in yourAccomodationImageModel as such:

    public static override bool operator ==(AccommodationImageModel a, AccommodationImageModel b)
    {
        return a.Id == b.Id;
    }
    

    Then when comparing just check the master list against the comparer list and remove those in the master list that don't have an identical object in the comparer list:

    List rem = new List;
    List newobj = new List;
    foreach(AccomodationImageModel a in compareList) {
              if(a.Id == 0) { // id == 0 => new item
                     newobj.Add(a); // add new item later
              } else {
                     // check those existing items as to whether they need to be updated or removed
                     bool match = false;
                     foreach(AccomodationImageModel b in masterList) {
                          if(a == b) match = true; // match found
                     }
                     if(!match) rem.Add(a); else Update(a); // will be removed or updated
              }
    }
    // now remove unmatched items
    foreach(AccomodationImageModel a in rem) { masterList.Remove(a); }
    foreach(AccomodationImageModel a in newobj) { AddNew(a); }
    

    Note Update(AccomodationImageModel a) is your method to update a certain item and AddNew(AccomodationImageModel a) is your method of insterting a new item in the master list.

    Also as you may have noteiced removing from and inserting to the master list should be done after you have looped the master list!

提交回复
热议问题