如何使EqualityComparer与两个字段进行比较?

时间:2014-01-08 18:29:20

标签: c# linq lambda iequalitycomparer

我们的代码库目前有以下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

1 个答案:

答案 0 :(得分:4)

使用匿名对象:

var userBooksToAdd = model.UserBooks.Exclude(currentUserBooksFromDatabase, 
    d => new{ d.Id, d.BookId }).ToList();

请注意,匿名对象不会使用Equals中定义的GetHashCodeobject实现。它们覆盖它们以对每个字段进行成员比较,因此这将按预期工作。