3
我們的代碼庫目前有以下EqualityComparer。如何使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
過載,但我m真的超過了我的頭與EqualityComparer
你沒關係構建一個自定義的相等比較器嗎?你不希望'Default'會以某種方式完成這項工作? –
會在鍵選擇器中返回一個匿名對象嗎? '排除(currentUserBooksFromDatabase,d => new {d.Id,d.Name})'只是一個猜測。 – Bort