Last active
April 11, 2021 09:28
-
-
Save ricardoboss/5bf617f846d7dcafcf26c4b49d6c16b1 to your computer and use it in GitHub Desktop.
Generic implementation for syncing an ICollection with an IEnumerable
This file contains 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
namespace System.Linq | |
{ | |
public static class CollectionExtensions | |
{ | |
public static void Sync<T>(this ICollection<T> source, IEnumerable<T> other, IEqualityComparer<T>? comparer = null) | |
{ | |
comparer ??= EqualityComparer<T>.Default; | |
var itemsToAdd = other.Except(source, comparer); | |
var itemsToRemove = source.Except(other, comparer); | |
foreach (var item in itemsToAdd) | |
source.Add(item); | |
foreach (var item in itemsToRemove) | |
source.Remove(item); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment