我找不到带有lambda(x => x.ID.Equals(newItem.ID((的旧Item - 因为它是泛型的。我可以提供另一个参数,如 ID 并使用它来获取属性的值(通过反射( - 但这真的是要走的路还是有更好的方法?
private void LogDiff<T>(HashSet<T> newList, HashSet<T> oldList)
{
Parallel.ForEach(newList, newItem =>
{
var oldItem = oldList.FirstOrDefault(x => x.ID.Equals(newItem.ID));
if (oldItem!= null)
{
//Yay i found my item
});
}
不,您通常通过另一个参数提供 ID 投影:
// Parameters renamed as they're not lists...
private void LogDiff<T, TKey>(HashSet<T> newItems, HashSet<T> oldItems,
Func<T, TKey> keySelector)
{
var comparer = EqualityComparer<TKey>.Default;
Parallel.ForEach(newItems, newItem =>
{
var newKey = keySelector(newItem);
var oldItem = oldList.FirstOrDefault(x => comparer.Equals(newKey, keySelector(x));
if (oldItem != null)
{
// Use the item
}
});
}
但是,与仅使用 Join
相比,效率相当低下 - 仍然可以并行执行:
var query = newItems.AsParallel()
.Join(oldItems.AsParallel(), keySelector, keySelector,
(n, o) => new { NewItem = n, OldItem = o });