Skip to content

Instantly share code, notes, and snippets.

@ricardoboss
Last active April 11, 2021 09:28
Show Gist options
  • Save ricardoboss/5bf617f846d7dcafcf26c4b49d6c16b1 to your computer and use it in GitHub Desktop.
Save ricardoboss/5bf617f846d7dcafcf26c4b49d6c16b1 to your computer and use it in GitHub Desktop.
Generic implementation for syncing an ICollection with an IEnumerable
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