【问题标题】:C# how do you remove a duplicate object in a list - where the object itself is complex and also has lists [duplicate]C#如何删除列表中的重复对象-对象本身很复杂并且也有列表[重复]
【发布时间】:2021-04-16 15:21:26
【问题描述】:

我有一个 c# 列表 ComplexTypeObj

类 ComplexTypeObj - 具有以下 3 个属性

搜索 = 新列表(复杂对象)

Ids= 新列表(guid 类型)

姓氏 = 列表(字符串类型)

我需要一种方法来确定列表中是否存在重复的 ComplexTypeObj,其中每个属性都匹配,但我在这个逻辑上遇到了一点问题?

【问题讨论】:

  • 在您的 ComplexTypeObj 类上实现 IEquatable<T> 并在列表中使用 HashSet.SetEquals。等
  • IEquatable 和 GetHashcode ;)
  • 谢谢,我已经为 equals 实现了 Iequatable public bool Equals([AllowNull] ComplexTypeObj other) { return this.Searches .Equals(other.Searches) && this.Ids.Equals(other .ids) && this.Surnames Equals(other.Surnames); } 我将如何使用 HashSet.SetEquals?

标签: c# linq


【解决方案1】:

这对你来说可能有点过头了,但我最喜欢的用于比较复杂对象的库是 CompareNETObjects

GitHubhttps://github.com/GregFinzer/Compare-Net-Objects

NuGet:安装包 CompareNETObjects -Version 4.73.0)

这是一个带有工作示例的 .NET Fiddle:https://dotnetfiddle.net/vP2ya3

    // This is the comparison class
    var compareLogic = new CompareLogic();

    // (Optionally define some configurations for the CompareLogic)
    // e.g. Compare different types, Ignore props, Case sensitivity, etc. 

    compareLogic.Config.IgnoreProperty<ComplexTypeObj>(x => x.Searches);
    compareLogic.Config.TreatStringEmptyAndNullTheSame = true;
    compareLogic.Config.CaseSensitive = true;

    // Compare the results
    var compareResults = compareLogic.Compare(cto3, cto1); // Where the magic happens.
    
    // Check if objects are equal
    if(!compareResults.AreEqual)
    {
      // Do something...
    }

    

但除了检查它们是否相等之外,返回的ComparisonResult 对象将让您查看对象属性之间的个体差异或获取所有属性差异的字符串,仅作为几个示例。

【讨论】:

    猜你喜欢
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多