user10503656
user10503656

Reputation:

SequenceEqual does not work below in comparing class

I am trying to compare the following data below. How come SequenceEqual does not work below? I created two list classes, and want to compare.

        public partial class Product
        {
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            public string ProductDescription { get; set; }
        }

        List<Product> product1 = new List<Product>();
        List<Product> product2 = new List<Product>();

        product1.Add(new Product
        {
            ProductId = 1,
            ProductName = "TV",
            ProductDescription = "Television Set"
        });

        product2.Add(new Product
        {
            ProductId = 1,
            ProductName = "TV",
            ProductDescription = "Television Set"
        });


        if (product1.SequenceEqual(product2))
        {
            Console.WriteLine("equal data");
        }
        else
        {
            Console.WriteLine("Not equal data");
        }

Upvotes: 0

Views: 1143

Answers (2)

Simply Ged
Simply Ged

Reputation: 8672

SequenceEqual compares the two sequences to see if the contain the same objects. In your case they don't. They contain different Product references.

If you change your code to use the same Product in each list then SequenceEqual will return `true'

var product = new Product
{
    ProductId = 1,
    ProductName = "TV",
    ProductDescription = "Television Set"
};

product1.Add(p);
product2.Add(p);


if (product1.SequenceEqual(product2))
{
    Console.WriteLine("equal data");
}
else
{
    Console.WriteLine("Not equal data");
}

Why? Because in this example the lists contain the same object.

Read this for more information on how SequenceEqual compares the two sequences.

If you want SequenceEqual to return true if the properties of the Product class are the same then you need to override the Equals method on the Product class.

EDIT

As others have mentioned, it is a better practice to implement the IEqualityComparer<T> interface instead of directly overriding the Equals method.

Upvotes: 2

Micka&#235;l Derriey
Micka&#235;l Derriey

Reputation: 13724

By default, the SequenceEqual method compares elements in the collection using the default comparer, which does a reference comparison — See the official documentation page, especially the Examples section.

If you want to compare the data of the objects rather than the references, you have two options (that I took from the page linked above):

  • have the Product class implement the IEquatable<Product> interface; or
  • create a separate class that implements the IEqualityComparer<Product> interface and use the overload of SequenceEqual that takes an instance of IEqualityComparer<T>

I suggest that you read the documentation page for more detailed information and examples on how to implement these two options.

Upvotes: 1

Related Questions