CStark
CStark

Reputation: 11

Generic method to compare two lists

I have 5 sets of lists that I need to compare. The requirement is to do this using a generic method.

For example, I have lists Teacher and Student. Teacher has TeacherId as its identifier, while Student has StudentId. Is it possible to create a method that would take in:

var result = Compare (teacherA, teacherB, "TeacherId");
var result = Compare (studentA, studentB, "StudentId");

It's probably something similar to the top answer here: How can I create a generic method to compare two list of any type. The type may be a List of class as well

But does it mean I have to create 5 IComparable methods per each list type? Sorry I'm very new to C#.

Upvotes: 0

Views: 135

Answers (3)

user2023861
user2023861

Reputation: 8208

You should use interfaces for this.

interface ICompareById {
    int Id { get; }
}

class Student : ICompareById {
    int Id { get; set; }
    int StudentId { get { return this.Id; }
}

class Teacher : ICompareById {
    int Id { get; set; }
    int TeacherId { get { return this.Id; }
}

class IdComp : IComparer<ICompareById>
{
    int Compare(ICompareById x, ICompareById y)
    {
        return Comparer<int>.Default.Compare(x.Id, y.Id);
    }
}

To find common elements:

teacherList.Intersect(studentList, new IdComp());

Upvotes: 0

Igor
Igor

Reputation: 62213

Depending on what you are doing your types should implement one or both of these interfaces: IEquitable if you just want to see if they are the same. IComparable if you want to order/sort the instances.

The implementation should be done on the type so Student and Teacher would both implement these interface(s). If you wanted to compare Student to Teacher you can implement the same interface using different generic arguments (ie. class Student : IEquitable<Student>, IEquitable<Teacher>)

There is no need to use generics here.

Upvotes: 2

Vladimir Arustamian
Vladimir Arustamian

Reputation: 842

It seems like you have pretty similar classes and you can create a base class like Person, for example, with property Id and then override it in inherited classes. After that, you can compare Ids.

public class Person
{
    public virtual string Id { get; set; }

    // ...
}

public class Student : Person
{
    public override string Id { get; set; }

    // ...
}

// ...

Upvotes: 0

Related Questions