egyeneskanyar
egyeneskanyar

Reputation: 167

Compare 2 Objects of Generic Class Type in C#

I have a homework and I have to compare 2 object's by one of their properties, but since I'm working with generic types on my linked list where I have to store the objects I can't really reach the object's certain property (I'm using an interface, and all of the classes implement that interface) So I have got a major interface, and some classes (i.e. class1, class2) that inherit the interface properties such as Age, or any kind of number that is comparable easily. In Main() I just created a new LinkedList and created some class1, class2 objects. I put them in the ordered list with that SortedListAddElement method, but I'm stuck at the part where it should compare the element's by the int properties. How should I go on from there with this source code? Should I change the first line to: class List : IEnumerable, IComparable, IMajorInterface? Or change something in CompareTo()? Please help!

interface IMajorInterface 
{ 
    string Name{ get; } 
    int Age { get; set; } 
}

class List<T> : IEnumerable<T>, IComparable<T>
{
    ListElement<T> head;

    public List()
    {
        head = null;
    }

    public void SortedListAddElement(T newValue)
    {
        ListElement<T> new = new ListElement<T>(newValue);
        ListElement<T> p = head;
        ListElement<T> e = null;
        while (p != null /* && this is the part where I should compare the p and new objects by their property, for example the Age property, like: p.Age < new.Age */)
        {
            e = p;
            p = p.Next;
        }
        if (e == null)
        {
            new.Next = head;
            head = new;
        }
        else
        {
            new.Next = p;
            e.Next = new;
        }
    }

    public int CompareTo(T obj)
    {
        if (obj == null)
        {
            return -1;
        }
        else
        {
            if (obj is T)
            {
                T obj2 = obj as T;
                return obj.Age.CompareTo(obj2.Age);
            }
            else
            {
                return -1;
            }
        }
    }

Upvotes: 0

Views: 2233

Answers (3)

Leandro
Leandro

Reputation: 1555

There are several options to solve that. Here is one approach. First, make your major interface comparable:

interface IMajorInterface : IComparable<IMajorInterface>
{
    string Name{ get; }
    int Age { get; set; }
}

Then constrain your generic type parameter in the list class implementation:

class List<T> : IEnumerable<T>
    where T : IComparable<T>
{
    // ... Code omitted for brevity.
}

Then implement the IComparable interface in your concrete major classes (class1, class2). Maybe it would be advisable to implement a base class for those, implement the interface there and derive the class1 and class2, etc. from that base class. Perhaps it would be even better to drop the IMajorInterface altogether and just make an abstract Major base class.

Alternatively, as you are only using the list for majors, you could just constrain the generic list parameter to the IMajorInterface or Major base class itself. That would be the simplest (and least flexible) solution:

class List<T> : IEnumerable<T>
    where T : IMajorInterface // No need to implement IComparable<T> in any class.
{
    // ... Code omitted for brevity.
}

Finally, as another approach, you could provide an IComparer<T> to the list on its constructor, just as the System.Collections.Generic classes do. Investigate on MSDN.

I hope it helps. Happy coding!

Upvotes: 4

user3403437
user3403437

Reputation: 117

you can implement IComparer.

class ageComparer : IComparer<Person>
   {
        public int Compare(Person x, Person y)
        {
            return x.Age - y.Age;
        }
   }

Have a look at this article http://www.blackwasp.co.uk/IComparer_2.aspx

Upvotes: 3

B.K.
B.K.

Reputation: 10152

Here's an article at c-sharpcorner that compares generic types:

http://www.c-sharpcorner.com/UploadFile/1a81c5/compare-2-objects-of-generic-class-type-in-C-Sharp/

Quick code snippet:

 static bool Compare<T>(T Object1, T object2)
 {
      //Get the type of the object
      Type type = typeof(T);

      //return false if any of the object is false
      if (Object1 == null || object2 == null)
         return false;

     //Loop through each properties inside class and get values for the property from both the objects and compare
     foreach (System.Reflection.PropertyInfo property in type.GetProperties())
     {
          if (property.Name != "ExtensionData")
          {
              string Object1Value = string.Empty;
              string Object2Value = string.Empty;
              if (type.GetProperty(property.Name).GetValue(Object1, null) != null)
                    Object1Value = type.GetProperty(property.Name).GetValue(Object1, null).ToString();
              if (type.GetProperty(property.Name).GetValue(object2, null) != null)
                    Object2Value = type.GetProperty(property.Name).GetValue(object2, null).ToString();
              if (Object1Value.Trim() != Object2Value.Trim())
              {
                  return false;
              }
          }
     }
     return true;
 }

Upvotes: 2

Related Questions