-1

I have a c# list ComplexTypeObj

The class ComplexTypeObj - has the following 3 properties

Searches = new List (complex object)

Ids= new List (guid type)

Surnames = List (string type)

I need a way to find out if there are duplicate ComplexTypeObj in the list where each of the properties match but I'm having a little trouble with the logic on this one?

Calibre2010
  • 3,729
  • 9
  • 25
  • 35
  • Implement `IEquatable` on your ComplexTypeObj class and use `HashSet.SetEquals` on the lists. etc. – Ian Mercer Apr 16 '21 at 15:35
  • IEquatable and GetHashcode ;) – Ralf Apr 16 '21 at 15:37
  • Thanks, I have implemented Iequatable for the equals public bool Equals([AllowNull] ComplexTypeObj other) { return this.Searches .Equals(other.Searches) && this.Ids.Equals(other.Ids) && this.Surnames Equals(other.Surnames); } how would I use the HashSet.SetEquals? – Calibre2010 Apr 16 '21 at 17:07

1 Answers1

0

This may be overkill for your purposes, but my favorite library for comparing complex objects is CompareNETObjects

(GitHub: https://github.com/GregFinzer/Compare-Net-Objects)

(NuGet: Install-Package CompareNETObjects -Version 4.73.0)

Here is a .NET Fiddle with a working example: 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...
    }

    

But in addition to just checking if they are equal, the ComparisonResult object returned will let you view individual differences between object properties or get a string of all property differences just as a few examples.

Stemado
  • 599
  • 5
  • 10