I implemented this extension method to synchronize a collection from another that can be of different type:
public static void Synchronize<TFirst, TSecond>(
this ICollection<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, bool> match,
Func<TSecond, TFirst> create)
{
var secondCollection = second.ToArray();
var toAdd = secondCollection.Where(item => !first.Any(x => match(x, item))).Select(create);
foreach (var item in toAdd)
{
first.Add(item);
}
var toRemove = first.Where(item => !secondCollection.Any(x => match(item, x))).ToArray();
foreach (var item in toRemove)
{
first.Remove(item);
}
}
ReSharper give me two "Implicitly captured closure", one on the first Where and one on the second, is there a way to fix it? I cannot find one.
[Update]
Based on the observation of Eric, I wrote a version that is faster than the one with the equals function, using instead the hash:
public static void Synchronize<TFirst, TSecond>(
this ICollection<TFirst> first,
IEnumerable<TSecond> second,
Func<TSecond, TFirst> convert,
Func<TFirst, int> firstHash = null,
Func<TSecond, int> secondHash = null)
{
if (firstHash == null)
{
firstHash = x => x.GetHashCode();
}
if (secondHash == null)
{
secondHash = x => x.GetHashCode();
}
var firstCollection = first.ToDictionary(x => firstHash(x), x => x);
var secondCollection = second.ToDictionary(x => secondHash(x), x => x);
var toAdd = secondCollection.Where(item => firstCollection.All(x => x.Key != item.Key)).Select(x => convert(x.Value));
foreach (var item in toAdd)
{
first.Add(item);
}
var toRemove = firstCollection.Where(item => secondCollection.All(x => x.Key != item.Key));
foreach (var item in toRemove)
{
first.Remove(item.Value);
}
}