5

I want to know how can I compare two objects (which is of the same class) like the string.Compare() method.

Is there any way to do this?

Aristos
  • 66,005
  • 16
  • 114
  • 150
Pankaj Kumar
  • 655
  • 3
  • 10
  • 16
  • check this link http://stackoverflow.com/questions/5183929/comparing-two-objects – Nitin Varpe Dec 24 '13 at 07:16
  • http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx – Prashant Mehta Dec 24 '13 at 07:18
  • The duplicate is the wrong one: The question asks about *comparing* two objects the same way `string.Compare` does, while the duplicate asks about *equating* two objects. The most voted answer here exactly answers what's being asked. – OfirD Sep 16 '20 at 18:45

5 Answers5

10

You can implement IComparable interface, like sugested here:

public class Temperature : IComparable 
{
    // The temperature value 
    protected double temperatureF;

    public int CompareTo(object obj) {
        if (obj == null) return 1;

        Temperature otherTemperature = obj as Temperature;
        if (otherTemperature != null) 
            return this.temperatureF.CompareTo(otherTemperature.temperatureF);
        else 
           throw new ArgumentException("Object is not a Temperature");
    }
  ...

source

You will have CompareTo method which will compare items of your class. More on IComparable can be found here on SO. Having CompareTo you can sort lists of your objects according to comparision function like mentioned here

Community
  • 1
  • 1
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
2

since objects are reference types, so you should use obj.Equals() method. also note that:

string.ReferenceEquals(str, str2);

It obviously compares references.

str.Equals(str2) 

Tries to compare references at first. Then it tries to compare by value.

str == str2

Does the same as Equals.

Zeeshan
  • 2,884
  • 3
  • 28
  • 47
1

You need to implement the IComparable interface.

private class sortYearAscendingHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
      car c1=(car)a;
      car c2=(car)b;
      if (c1.year > c2.year)
         return 1;
      if (c1.year < c2.year)
         return -1;
      else
         return 0;
   }
}

Original post can be found Here

Ramashankar
  • 1,598
  • 10
  • 14
1

You can check two equality Reference Equality and Value Equality

Reference equality

Reference equality means that two object references refer to the same underlying object. This can occur through simple assignment, as shown in the following example.

class Test
{
    public int Num { get; set; }
    public string Str { get; set; }

    static void Main()
    {
        Test a = new Test() { Num = 1, Str = "Hi" };
        Test b = new Test() { Num = 1, Str = "Hi" };

        bool areEqual = System.Object.ReferenceEquals(a, b);
        // Output will be false
        System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);

        // Assign b to a.
        b = a;

        // Repeat calls with different results.
        areEqual = System.Object.ReferenceEquals(a, b);
        // Output will be true
        System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);


    }
}

Value equality

Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.

pravprab
  • 2,301
  • 3
  • 26
  • 43
Kumod Singh
  • 2,113
  • 1
  • 16
  • 18
0
public class BaseEntity
{
    public int Id { get; set; }
}

public class Product : BaseEntity
{
   public string Name { get; set; }
   public decimal Price { get; set; }
}

//Generic Comparer
public class EntityComparer<T> :  IEqualityComparer<T>, IComparer<T> 
where T : BaseEntity
{
    public enum AscDesc : short
    {
        Asc, Desc
    }

    #region Const
    public string PropertyName { get; set; }
    public AscDesc SortType { get; set; }
    #endregion

    #region Ctor
    public EntityComparer(string _propertyname = "Id", AscDesc _sorttype = AscDesc.Asc)
    {
        this.PropertyName = _propertyname;
        this.SortType = _sorttype;
    }
    #endregion

    #region IComparer
    public int Compare(T x, T y)
    {
        if (typeof(T).GetProperty(PropertyName) == null)
            throw new ArgumentNullException(string.Format("{0} does not contain a property with the name \"{1}\"", typeof(T).Name, PropertyName));

        var xValue = (IComparable)x.GetType().GetProperty(this.PropertyName).GetValue(x, null);
        var yValue = (IComparable)y.GetType().GetProperty(this.PropertyName).GetValue(y, null);

        if (this.SortType == AscDesc.Asc)
            return xValue.CompareTo(yValue);

        return yValue.CompareTo(xValue);
    }
    #endregion

    #region IEqualityComparer
    public bool Equals(T x, T y)
    {
        if (typeof(T).GetProperty(PropertyName) == null)
            throw new InvalidOperationException(string.Format("{0} does not contain a property with the name -> \"{1}\"", typeof(T).Name, PropertyName));

        var valuex = x.GetType().GetProperty(PropertyName).GetValue(x, null);
        var valuey = y.GetType().GetProperty(PropertyName).GetValue(y, null);

        if (valuex == null) return valuey == null;

        return valuex.Equals(valuey);
    }

    public int GetHashCode(T obj)
    {
        var info = obj.GetType().GetProperty(PropertyName);
        object value = null;
        if (info != null)
        {
            value = info.GetValue(obj, null);
        }

        return value == null ? 0 : value.GetHashCode();
    }
    #endregion
}

 //Usage
 Product product = new Product();
 Product product2 =new Product();
 EntityComparer<Product> comparer = new EntityComparer<Product>("Propert Name Id Name whatever u want", Asc Or Desc);
 comparer.Compare(product, product2);