Question

I have two lists of Student Object in my code List<student> list1 and List<student> list2. The student object has the following properties. FirstName LastName University

I have the following method where I would like to compare the value of the respective property between the objects in the two list using LINQ. I found a few examples in LINQ that showed how to compare two values in a list of integers or string, but could not find any examples that compares the property value of the objects in the List.

`private CompareList(ref List<student> L1,ref List<student> L2)
 {
   // compare FirstName of L1 to L2
      ......

 }`

How would I go about doing this? Thanks!

Was it helpful?

Solution

public static bool Compare(ref List<Student> list1, ref List<Student> list2)
{
        return Enumerable.SequenceEqual(list1,list2, new MyCustomComparer());
}

public class MyCustomComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        if (x.FirstName == y.FirstName && x.LastName == y.LastName && x.University == y.University)
            return true;
        return false;
    }

    public int GetHashCode(Student obj)
    {
        throw new NotImplementedException();
    }
}

OTHER TIPS

You didn't say what exactly you want to check, but if you just want to know if two collections are equal then I guess you could check it this way:

bool isAnyElementFromL1NotInL2 = L1.Select(x => x.Name).Except(L2.Select(y => y.Name)).Any();
bool isAnyElementFromL2NotInL1 = L2.Select(x => x.Name).Except(L1.Select(y => y.Name)).Any();
bool areL1AndL2TheSame = !isAnyElementFromL1NotInL2 && !isAnyElementFromL2NotInL1;

See also this answer by Jon Skeet

Or this question.

The best ways to do it would be to either the student (types are conventionally Pascal cased) being comparable by implementing the IComparable<student>/IStructuralComparable or IEquatable<student>/IStructuralEquatable or by creating a comparer class implementing IComparaer<T>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top