【问题标题】:Compare Two Custom list objects by Ignoring few properties [closed]通过忽略一些属性来比较两个自定义列表对象[关闭]
【发布时间】:2019-02-16 02:46:45
【问题描述】:

我有两个具有以下属性的自定义列表对象:ID(AutoGenerated -Guid)、EmpoyeeID、Firstname、lastname 和 Employstatus。

我想使用 Except() 关键字来比较两个列表的差异,但我想专门忽略 ID 属性。

如何忽略 ID 属性来查找两个列表之间的差异?

【问题讨论】:

标签: c# linq


【解决方案1】:

您可以创建自己的 IEqualityComparer 自定义实现,如下所示:

这是一个 Fiddle 示例,其中应返回 List1 中的最后四名员工:https://dotnetfiddle.net/f3sBLq

在此示例中,EmployeeComparer 继承自 IEqualityComparer<Employee>,其中 Employee 是具有您列出的属性(EmployeeID、Firstname、Lastname、Employmentstatus)的类

public class EmployeeComparer : IEqualityComparer<Employee>
{
    public int GetHashCode(Employee co)
    {
        if (co == null)
        {
            return 0;
        }

        //You can use any property you want (other than EmployeeID for your purposes); the GetHashCode metho is used to generate an address to where the object is stored
        return co.Employmentstatus.GetHashCode();
    }

    public bool Equals(Employee x1, Employee x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }

        if (object.ReferenceEquals(x1, null) || object.ReferenceEquals(x2, null))
        {
            return false;
        }

        // Check for equality with all properties except for EmployeeID
        return x1.Employmentstatus == x2.Employmentstatus && x1.Firstname == x2.Firstname && x1.Lastname == x2.Lastname;
    }
}

然后你可以这样使用它:

var results = List2.Except(List1, new EmployeeComparer()).ToList();

编辑:原始问题未将 ID 列为属性,并要求如何排除 EmployeeID,这是此答案和 Fiddle 链接示例均基于的内容。

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多