【问题标题】:Compare object properties in 2 lists比较 2 个列表中的对象属性
【发布时间】:2017-12-11 14:56:34
【问题描述】:

在其他一些问题中,我发现了有关如何比较两个对象列表并在列表中的对象不同的意义上获得差异的信息。 如果我在两个列表中有相同的对象,但两个列表中的特定对象的属性值可能不同,我不确定是否可能发生相同/相似的事情。

是否有检查这种情况的快捷方式?

【问题讨论】:

  • 我不确定我是否正确理解了您的问题,但您可以覆盖列表中存储的对象的Equals 方法,然后将其与该方法进行比较。使用这种方法,您可以自己定义对象是否相等。
  • 一些典型输入的示例以及由此产生的所需输出将使这一点更加清晰。你的描述有点模糊。我想这是完全有可能的,但不清楚你在说什么确切的情况或数据结构。

标签: c# list compare


【解决方案1】:

我认为this page:上描述了您想要的内容

示例(从上面链接的 MSDN 站点复制以将答案保留在 StackOverflow 上):

// This class defines your objects with your properties.
public class ProductA
{ 
    public string Name { get; set; }
    public int Code { get; set; }
}

// This class is used for custom comparison.
public class ProductComparer : IEqualityComparer<ProductA>
{

    public bool Equals(ProductA x, ProductA y)
    {
        //Check whether the objects are the same object. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether the products' properties are equal. 
        return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
    }

    public int GetHashCode(ProductA obj)
    {
        int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();
        int hashProductCode = obj.Code.GetHashCode();
        return hashProductName ^ hashProductCode;
    }
}

你现在可以这样使用它:

ProductA[] fruits1 = { new ProductA { Name = "apple", Code = 9 }, 
                   new ProductA { Name = "orange", Code = 4 },
                    new ProductA { Name = "lemon", Code = 12 } };

ProductA[] fruits2 = { new ProductA { Name = "apple", Code = 9 } };

// Get all the elements from the first array except for the elements from the second array.    
IEnumerable<ProductA> except = fruits1.Except(fruits2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-26
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多