Home > Back-end >  Check for identical objects
Check for identical objects

Time:10-24

How i cant check objects for equality? I have 2 objects of Class Storage(with List of class products) and i want to find mutual products, but when i check Identical 2 objects of Product, they aren't identical.

class Storage
    {
       public List<Product> many_product;
       public Storage(List<Product> el)
        {
            this.many_product.AddRange(el);
        }
        public static Storage mutual_products(Storage a, Storage b)
        {
            Storage mutal_products = new Storage();
            foreach (var prod in a.many_product)
                if (b.many_product.Contains(prod))// return false, but in list is a mutual product
                {
                    mutal_products.many_product.Add(prod);
                }
            return mutal_products;
        }
     }

The same when i check identical product with if(prod1==prod2)//return false

CodePudding user response:

Your product class should implement IEquatable<Product> interface for the Contains method to work properly. For example:

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

    public double Price { get; set; }

    public bool Equals(Product other)
    {
        return Name.Equals(other.Name)
            && Price.Equals(other.Price);
    }
}

If you are using .NET 5 & C# 9, you can make your Product class a record. Then there will be no need to implement IEquatable<Product> explicitly.

CodePudding user response:

There are several possibilities to do deep comparison (including all nested properties) of objects: using reflection, serialization and so on. look answers here for details

For my own needs, I wrote my own universal object comparator

  •  Tags:  
  • c#
  • Related