开发者

EqualityComparer in LINQ - how can I do?

I think that the code below is good. But how can I write it in LINQ? how can I compare Employee type object in linq?

namespace GenericReplacement
{
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeComparer employeeComparer = new EmployeeComparer();

            Employee employee1 = new Employee() { ID = 1, Name = "yusuf", SurName = "karatoprak" };
            Employee employee2 = new Employee() { ID = 2, Name = "Ali", SurName = "Yılmaz" };

            bool returnValue = employeeComparer.Equals(employee1, employee2);
            int returnValueHashCode = employeeComparer.GetHashCode(employee1);

            Console.WriteLine("Result: "+returnValue.ToString()+"\n");
            Console.WriteLine(returnValueHashCode.ToString());
            Console.ReadKey();
        }
    }

    public class EmployeeComparer: EqualityComparer<Employee>
    {
        public override bool Equals(Employee x, Employee y)
        {
            return EqualityComparer<Employee>.Default.Equals(x, y);
        }

      开发者_C百科  public override int GetHashCode(Employee obj)
        {
            return EqualityComparer<Employee>.Default.GetHashCode(obj);
        }
    }

    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }
}


LINQ isn't meant to replace all existing code. LINQ is paticularly good for some tasks (for example querying collections or databases), but it's not meant to be used for everything.

If you have enumerables of employees then it might make sense to use LINQ to compare the two enumerables. For example you could use the overload of Enumerable.SequenceEqual that takes a comparer:

bool result = Enumerable.SequenceEqual(first, second, comparer);

For comparing two single items using LINQ doesn't seem to be necessary.


not sure why you need to do this as you normally would use LINQ if you wanted to do some action to a collection (query, etc) where these items would be. If for some reason you had to do this (again not sure why), you could do something like this:

 List<Employee> employees = new List<Employee>();
 employees.Add(employee1);

 List<Employee> employees2 = new List<Employee>();
 employees2.Add(employee2);

 IEnumerable<Employee> equalList = employees.Intersect(employees2, new EmployeeComparer());

 if (equalList.Count() == 0)
 {
       MessageBox.Show("Not equal");
 }
 else
 {
       MessageBox.Show("Equal");
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜