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

前端 未结 4 2104
时光取名叫无心
时光取名叫无心 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:36

        ///If image is not in list then add the image to the list
    
    public void AddNew (List masterList, AccomodationImageModel theImage)
    {
        masterList.Add(theImage);
    }
    
        /// If Image is in List then change listitem with new one
    
    public void Update (List masterList, int OldOnesID, AccomodationImageModel theNew)
    {
        masterList[OldOnesID] = theNew;
    }
    
        /// If Image should delete then removes the image from list
    
    public void Delete (List imgList, AccomodationImageModel theImageToDelete)
    {
        masterList.Remove(theImageToDelete);
    }
    
    
        /// this method checks the image state and do the work
    
    public void CheckState (List masterList, AccomodationImageModel theImage, bool deleteIt)
    {
    
    
           for(int i = 0; i < masterList.Count; i++)
           {
    
             if (deleteIt)
             {
                Delete(masterList, theImage);
             }
    
             else
             {
               if(theImage.ID == 0)
               {
                 AddNew(masterList, theImage);
               }
    
               if(masterList[i].ID == theImage.ID)
               {
                 Update(masterList, i, theImage);
               }
           }
    }
    

    If you prefer use 2 lists as a master and Temporary list, then you can simply iterate your temporary list and each of templist item use CheckState method..

    Hope this helps..

提交回复
热议问题