加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Linq不等于

发布时间:2020-12-15 18:31:29 所属栏目:百科 来源:网络整理
导读:我在C#app.A和B中有2个列表集合. 两个集合都有客户对象,具有Id和Name属性.通常,A有比B更多的项目. 使用Linq,我想只返回ID在A但不在B中的客户. 我该怎么做呢? 解决方法 有多种方法可以采取.如果你有覆盖Equals和GetHashCode,最干净的方法是使用Except扩展方
我在C#app.A和B中有2个列表集合.

两个集合都有客户对象,具有Id和Name属性.通常,A有比B更多的项目.

使用Linq,我想只返回ID在A但不在B中的客户.

我该怎么做呢?

解决方法

有多种方法可以采取.如果你有覆盖Equals和GetHashCode,最干净的方法是使用Except扩展方法.如果还没有,还有其他选择.
// have you overriden Equals/GetHashCode?
IEnumerable<Customer> resultsA = listA.Except(listB);

// no override of Equals/GetHashCode? Can you provide an IEqualityComparer<Customer>?
IEnumerable<Customer> resultsB = listA.Except(listB,new CustomerComparer()); // Comparer shown below

// no override of Equals/GetHashCode + no IEqualityComparer<Customer> implementation?
IEnumerable<Customer> resultsC = listA.Where(a => !listB.Any(b => b.Id == a.Id));

// are the lists particularly large? perhaps try a hashset approach 
HashSet<int> customerIds = new HashSet<int>(listB.Select(b => b.Id).Distinct());
IEnumerable<Customer> resultsD = listA.Where(a => !customerIds.Contains(a.Id));

class CustomerComparer : IEqualityComparer<Customer>
{
    public bool Equals(Customer x,Customer y)
    {
        return x.Id.Equals(y.Id);
    }

    public int GetHashCode(Customer obj)
    {
        return obj.Id.GetHashCode();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读