C # -Comparable <T> and IEquatable <T>

Possible duplicate:
What is the difference between IComparable and IEquatable?

What is the main difference between IComparable<T>and IEquatable<T>? When to use each of them specifically?

+3
source share
3 answers

IComparable determines the order (smaller, larger). The method he defines is CompareTo, with which you can determine the order between two elements.

IEquatable defines equality. The method he defines is equal to Equals; it allows you to determine if two elements are equal.

Compare the example by ordering Person by age:

public class Person : IComparable<Person>
{
    public int Age { get; set; }
    public int ID { get; set; }

    public int CompareTo(Person other)
    {

        return Math.Sign(Age - other.Age); // -1 other greater than this
                                           // 0 if same age
                                           // 1 if this greater than other
    }
}

Sorting:

[Test]
public void SortTest()
{
    var persons = new List<Person>
                      {
                          new Person { Age = 0 },
                          new Person { Age = 2 },
                          new Person { Age = 1 }
                      };

    persons.Sort();

    Assert.AreEqual(0, persons[0].Age);
    Assert.AreEqual(1, persons[1].Age);
    Assert.AreEqual(2, persons[2].Age);
}

Person by ID:

public class Person : IEquatable<Person>
{
    public int Age { get; set; }
    public int ID { get; set; }

    public bool Equals(Person other)
    {
        return ID == other.ID;
    }
}
+9

IEnumerable<T>,, IComparable<T>,, ; IEquatable<T>

+2

, , , IComparable , .Net , .
, - , -, IComparable, , - , , .

IEquatable , .Net , Equals. , . , , , , , . , , , , .

, , .Net . , Contains() , IEquatable

MSDN:

IEquatable < (Of < (T > ) > ) < (Of < (TKey, TValue > ) > ), List < (Of < (T > ) > ) LinkedList < (Of < (T > ) > ) , , IndexOf, LastIndexOf . , .

IComparable < (Of < (T > ) > ) . - , , . , List < (Of < (T > ) > )..::. Sort()()() Add

.

+1

Source: https://habr.com/ru/post/1722864/


All Articles