其他分享
首页 > 其他分享> > CodeGo.net>如何使一个EqualityComparer比较两个领域?

CodeGo.net>如何使一个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();

现在,我们需要与数据库中具有复合唯一性的两个字段进行比较

基本上

if(currentBooksFromDatabase.BookId == model.BookId && 
   currentBooksFromDatabase.UserId == model.Id)

我希望创建一个Exclude重载,但是我真的对EqualityComparer感到头疼

解决方法:

使用匿名对象:

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

请注意,匿名对象将不使用object中定义的Equals和GetHashCode实现.他们重写它们以对每个字段进行成员比较,因此这将按预期工作.

标签:iequalitycomparer,linq,c,lambda
来源: https://codeday.me/bug/20191030/1964512.html