I'm trying to use IEqualityComparer
to compare 2 fields from 2 collections field by field. IEqualityComparer
is comparing only 1 field "name". I want to compare "mark" as well.
In Java, we have comparator
interface to compare more than one fields in Equals
method.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
IList<Student> studentList1 = new List<Student>()
{
new Student(){ name="aaaaa", mark = 95, },
new Student(){ name="bbbb", mark = 25, },
new Student(){ name="ccc", mark = 80 }
};
IList<Student> studentList2 = new List<Student>()
{
new Student(){ name="aaaaa", mark = 95, },
new Student(){ name="bbbb", mark = 5, },
new Student(){ name="ccc", mark = 80 }
};
bool isEqual = studentList1.SequenceEqual(studentList2, new StudentComparer());
Console.WriteLine("Names in 2 collections are {0}", isEqual?"equal":"not equal");
}
}
public class Student
{
public string name { get; set; }
public int mark { get; set; }
}
public class StudentComparer : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
if (x.name == y.name)
return true;
return false;
}
public int GetHashCode(Student obj)
{
return obj.GetHashCode();
}
}
Actual Result: Names in 2 collections are equal Expected Result: Names in 2 collections are equal Marks in 2 collections are not equal