简体   繁体   中英

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#.

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.

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; }

    // ...
}

// ...

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM