我有两个系列。
var a = new List<string>() { "a", "b", "c", "d", "e", "f", "j" };
var b = new List<string>() { "a", "c", "d", "h", "i" };
而且我想对该项目执行一些操作,以防它在一个或另一个集合中丢失。
public static Synchronize<T>(IEnumerable<T> first, IEnumerable<T> second, Action<T> firstSynchronizer, Action<T> secondSynchronizer)
{
var firstUnique = first.Distinct();
var secondUnique = second.Distinct();
foreach (var item in firstUnique)
{
if (!secondUnique.Contains(item)) firstSynchronizer(item);
}
foreach (var item in second.Distinct())
{
if (!firstUnique.Contains(item)) secondSynchronizer(item);
}
}
这就是我得到的,但我对此并不满意。我不禁想知道是否有更好的方法来实现这一点,因为我认为对Distinct()
性能的影响很大,而且我不确定是否最好迭代整个第二个 Enumerable 并检查第一个 Enumerable 中是否不存在项目(像上面一样)还是迭代会更好second.Except(first)
?你们有什么感想?
我这样称呼它:
var a = new List<string>() { "a", "b", "c", "d", "e", "f", "j" };
var b = new List<string>() { "a", "c", "d", "h", "i" };
Synchronize(a.ToArray(), b.ToArray(), t => b.Add(t), t => a.Add(t));
我这样称呼ToArray()
集合在被迭代时不会被改变,而 lambdas 只是将缺失的元素添加到相应的列表中。
Also, this is just a test implementation. In production environment, Enumerables won't be of same type. This is intended to be used to sync remote and local storage. In future, Enumerable first will be for example ICollection<DummyRemoteItem>
and Enumerable second will be List<IO.FileSystemInfo>
. But I want it to be more generic. To make it possible to work with different collections, I think I would propose another type parameter and a Func<T1, T2, bool>
for comparing items. That would be a best approach, right?
Generally, what's the best way to implement insides of
Synchronize<T>(IEnumerable<T> first,IEnumerable<T> second,Action<T> firstSynchronizer,Action<T> secondSynchronizer)
and
Synchronize<TFirst, TSecond>(IEnumerable<TFirst> first,IEnumerable<TSecond> second,Action<TFirst> firstSynchronizer,Action<TSecond> secondSynchronizer, Func<TFirst, TSecond, bool> predicate)