c# - 使用 Linq 不等于

标签 c# linq

我的 C# 应用程序中有 2 个列表集合..A 和 B。

这两个集合都有具有 Id 和 Name 属性的客户对象。通常情况下,A 的项目比 B 多。

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

我该怎么做?

最佳答案

有多种方法可供选择。如果您覆盖了 EqualsGetHashCode,最干净的方法是使用 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();
    }
}

关于c# - 使用 Linq 不等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669507/

相关文章:

c# - 如何从 T-SQL 转换 Sum over partition

c# - 当 EF 是另一个项目时,DropCreateDatabaseIfModelChanges

C# - 为应用程序保留磁盘内存(存储)

c# - 在 .NET 中使用整数填充列表的更简单方法

c# - 我的 EF 查询有什么问题?

c# - 使用不为空的对象属性的 EF6 查询条件

c# - ToolStripStatusLabel 显示为黑框

c# - 在超出边界的某个步骤继续遍历数组

c# - 如何处理阻塞同步外部 DLL 方法

c# - Expression.MemberInit -- 最佳重载方法匹配有一些无效参数