public void Set(string key, List <RemoteModel> data) { var Key = Keys.FirstOrDefault(s => s.KeyStr == key) ?? new Key() { KeyStr = key }; foreach (var remoteModel in data) { var exist = MyModels.FirstOrDefault(s => s.RemoteModel.Id == remoteModel.Id); if (exist == null) { // add data to the cache var myModel = new MyModel() { RemoteModel = remoteModel }; var keyMyModel = new KeyMyModel() { Key = key, MyModelId = remoteModel.Id }; myModel.KeyMyModels.Add(keyMyModel); Key.KeyMyModels.Add(keyMyModel); Keys.Add(Key); } else { exist.RemoteModel = remoteModel; var existKeyMyModel = KeyMyModels.FirstOrDefault(s => s.Key == key && s.MyModelId == exist.RemoteModel.Id); if (existKeyMyModel == null) { existKeyMyModel = new KeyMyModel() { Key = key, MyModelId = exist.RemoteModel.Id }; Key.KeyMyModels.Add(existKeyMyModel); exist.KeyMyModels.Add(existKeyMyModel); KeyMyModels.Add(existKeyMyModel); } } } // Remove MyModels if need var remoteIds = data.Select(s => s.Id); var currentIds = KeyMyModels.Where(s => s.Key == key).Select(s => s.MyModelId); var removingIds = currentIds.Except(remoteIds); var removingKeyMyModels = KeyMyModels.Where(s => s.Key == key && removingIds.Any(i => i == s.MyModelId)).ToList(); removingKeyMyModels.ForEach(s => { KeyMyModels.Remove(s); Key.KeyMyModels.Remove(s); }); }