Last active
June 8, 2019 09:17
-
-
Save AlonAm/008c0a9edbb48d8b666277a28f9cc557 to your computer and use it in GitHub Desktop.
Collection Synchronizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class CollectionSynchronizer<TSource, TDestination> | |
| { | |
| public Action<TSource> Add { get; set; } | |
| public Action<TDestination> Remove { get; set; } | |
| public Action<TSource, TDestination> Update { get; set; } | |
| public Func<TSource, TDestination, bool> Compare { get; set; } | |
| /// <summary> | |
| /// Synchronize changes from source to destination collection. | |
| /// Source collection is not changed. | |
| /// </summary> | |
| public void Synchronize(ICollection<TSource> sourceItems, ICollection<TDestination> destinationItems) | |
| { | |
| RemoveItems(sourceItems, destinationItems); | |
| AddOrUpdateItems(sourceItems, destinationItems); | |
| } | |
| /// <summary> | |
| /// Remove items from destination collection. | |
| /// </summary> | |
| private void RemoveItems(ICollection<TSource> sourceCollection, ICollection<TDestination> destinationCollection) | |
| { | |
| foreach (var destinationItem in destinationCollection.ToArray()) | |
| { | |
| var sourceItem = sourceCollection.FirstOrDefault(item => Compare(item, destinationItem)); | |
| if (sourceItem == null) | |
| { | |
| Remove(destinationItem); | |
| } | |
| } | |
| } | |
| /// <summary> | |
| /// Add or update item in destination collection. | |
| /// </summary> | |
| /// <param name="sourceCollection"></param> | |
| /// <param name="destinationCollection"></param> | |
| private void AddOrUpdateItems(ICollection<TSource> sourceCollection, ICollection<TDestination> destinationCollection) | |
| { | |
| var destinationList = destinationCollection.ToList(); | |
| foreach (var sourceItem in sourceCollection) | |
| { | |
| var destinationItem = destinationList.FirstOrDefault(item => Compare(sourceItem, item)); | |
| if (destinationItem == null) | |
| { | |
| Add(sourceItem); | |
| } | |
| else | |
| { | |
| Update(sourceItem, destinationItem); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment