简体   繁体   中英

Test equality of two lists

I have to check equality of two lists including their elements and also their sequence. I am using following but it is not working

    public class SampleClass
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    [TestMethod]
    public void EqualityTest()
    {
        var list1 = new List<SampleClass>
        {
            new SampleClass {Id  = "11", Name = "abc"},
            new SampleClass {Id  = "22", Name = "xyz"}
        };
        var list2 = new List<SampleClass>
        {
            new SampleClass {Id  = "11", Name = "abc"},
            new SampleClass {Id  = "22", Name = "xyz"}
        };
        Assert.IsTrue(Enumerable.SequenceEqual(list1, list2));
    }

please suggest any solution.

As you've not overridden Equals or implemented IEquatable<SampleClass> you're just getting the default comparison, which checks if the references are equal.

You want something like this:

public class SampleClass : IEquatable<SampleClass>
{
    public string Id { get; set; }
    public string Name { get; set; }

    public bool Equals(SampleClass obj)
    {
      if(obj == null) return false;

      return obj.Id == this.Id && obj.Name == this.Name
    }

    public override bool Equals(object obj) => Equals(obj as SampleClass);
}

I would recommend using deep comparsion library, like Compare-Net-Objects

Simply import NuGet package

Install-Package CompareNETObjects

And call the helper method

list1.ShouldCompare(list2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM