Next Olive
Next Olive

Reputation: 49

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.

Upvotes: 1

Views: 328

Answers (2)

Euphoric
Euphoric

Reputation: 12849

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);

Upvotes: 0

Sean
Sean

Reputation: 62472

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);
}

Upvotes: 3

Related Questions