0

I have a custom class that contains a string. My program has an array of these classes and I want to be able to compare one array of these to another.

I have implemented the IComparable interface as described here: http://www.informit.com/articles/article.aspx?p=25352&seqNum=4 but I find that this does not allow me to compare one array against another. (It allows me to sort the array)

public class MyClass : IComparable<MyClass>
    {
        #region Private
        private string _name;
        #endregion

        #region Public

        [XmlElement("Name")]
        public string Name
        {
            get{return _name;}
            set{_name= value;}
        }
        #endregion

        public int CompareTo(MyClass class)
        {
            string s1 = this.Name;
            string s2 = class.Name;
            return String.Compare(s1, s2);
        }

        override public string ToString()
        {
            return _name;
        }
    }

My program has an array of these classes like so:

MyClass class1 = new MyClass();
class1.Name = "a";

MyClass class2 = new MyClass();
class2.Name = "b";

MyClass class3 = new MyClass();
class3.Name = "c";

MyClass class4 = new MyClass();
class4.Name = "d";

MyClass[] classes1 = { class1, class2, class3}
MyClass[] classes2 = { class1, class2, class4};

I can sort the class if need be:

Array.Sort(classes2);

What interface do I need to implement to allow me to compare one array against another to see if they are equal?

EDIT My class is custom and does not inherit from any interfaces so I want to know what interface to implement, how to implement it and how to use it. This example uses objects which are not custom: Easiest way to compare arrays in C#

Community
  • 1
  • 1
Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • 1
    Sorry, I thought you were referring to sorting, not comparing :-P – CodeNaked Nov 10 '16 at 15:28
  • You create a comparer for the array in exactly the same way that you create the comparer for the single object. You create the comparer, and write whatever you want in the `Compare` method. What problem(s) did you have implementing that? – Servy Nov 10 '16 at 15:44

1 Answers1

0

Your class needs to override the Equals method.
Alternatively, you can implement the IEquatable interface.
You can then apply the "SequenceEquals" LINQ Operator to your arrays in order to achieve what you desire.

Eyal Perry
  • 2,255
  • 18
  • 26