CompareNetObjects - Ignore Comparison of null with an empty list / collection

Viewed 780

Hi I'm using ComparisonNetObjects Library:

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

I couldn't find in ComparisonConfig to disable comparing null with empty list/collection.

What would be the best way using CompareNetObjects to disable comparison of null and empty list/collection?

These are my classes:

public class Attachment {
    public int ID { get; set; }
    public string FileName { get; set; }
}


public class Priority {

    public int ID { get; set; }
    public int Order { get; set; }
    public string Title { get; set;}
}

public class Student 
{
    public string Name { get; set;}
    public int ID { get; set; }
    public List<Attachment> Attachments { get; set; }
    public Priority Priority { get; set; }
}

Example:

    Student aStudent = new Student() {
        Name = "John",
        ID = 1,
        Attachments = null,
        Priority = new Priority() {
            Title = "Low",
            Order = 1,
            ID = 1
        }
    };

    Student aStudent2 = new Student() {
        Name = "John",
        ID = 1,
        Attachments = new List<Attachment>() { },
        Priority = new Priority() {
            Title = "Medium",
            Order = 2,
            ID = 2
        }
    };

Here's my how I compare

ComparisonConfig cfg = new ComparisonConfig()
            {
                IgnoreObjectTypes = true,
                IgnoreCollectionOrder = true,
                IgnoreUnknownObjectTypes = true,
                ComparePrivateFields = false,
                ComparePrivateProperties = false,
                // I found custom solution but I find to be impractical if there are many list/collection
                MembersToIgnore = new List<string>() { /*ShouldIgnore(aStudent, aStudent2)*/ }, 
                MaxStructDepth = 1,
                MaxDifferences = 20,
                TreatStringEmptyAndNullTheSame = true,
               

            };
 CompareLogic compareLogic = new CompareLogic(cfg); 
 ComparisonResult compareNewWithOld = compareLogic.Compare(aStudent, aStudent2);
 if (compareNewWithOld.Differences.Count() > 0)
 {
    foreach (Difference diff in compareNewWithOld.Differences)
    {
        Console.WriteLine("Property name:" + diff.PropertyName);
        Console.WriteLine("Old value:" + diff.Object1Value);
        Console.WriteLine("New value:" + diff.Object2Value + "\n"); 
    }
 }

here's what I get

// I don't want this to be found as a difference because it's null with an empty list

Property name:Attachments
Old value:(null)
New value:System.Collections.Generic.List`1[Attachment]


//From here downwards is fine because there are differences
Property name:Priority.ID
Old value:1
New value:2


Property name:Priority.Order
Old value:1
New value:2


Property name:Priority.Title
Old value:Low
New value:Medium

0 Answers
Related