我们的代码库目前有以下EqualityComparer。
public static IEnumerable<TSource> Exclude<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer = null)
{
comparer = comparer ?? EqualityComparer<TKey>.Default;
var set = new HashSet<TKey>(second.Select(keySelector), comparer);
return first.Where(item => set.Add(keySelector(item)));
}
我们就这样使用它。
// Take the current model and remove all items currently in the database... This leaves us with only records that need to be added.
var userBooksToAdd = model.UserBooks.Exclude(currentUserBooksFromDatabase, d => d.Id).ToList();
我们现在需要与数据库中存在COMPOSITE UNIQUE
基本上
if(currentBooksFromDatabase.BookId == model.BookId &&
currentBooksFromDatabase.UserId == model.Id)
我希望创建一个Exclude
重载,但我真的很喜欢EqualityComparer
答案 0 :(得分:4)
使用匿名对象:
var userBooksToAdd = model.UserBooks.Exclude(currentUserBooksFromDatabase,
d => new{ d.Id, d.BookId }).ToList();
请注意,匿名对象不会使用Equals
中定义的GetHashCode
和object
实现。它们覆盖它们以对每个字段进行成员比较,因此这将按预期工作。