CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp
{
public class Person
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(int age, string firstName, string lastName)
{
Age = age;
FirstName = firstName;
LastName = lastName;
}
public override string ToString()
{
return $"Age = {Age}, FirstName = {FirstName}, LastName = {LastName}";
}
}
public class PersonEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null || y is null)
{
return false;
}
return x.Age == y.Age &&
x.FirstName == y.FirstName &&
x.LastName == y.LastName;
}
public int GetHashCode(Person obj)
{
if (obj == null)
{
return 0;
}
return HashCode.Combine(obj.Age, obj.FirstName, obj.LastName);
}
}
public class Program
{
public static void Main()
{
var list1 = new List<Person>
{
new Person(20, "first1", "last1"),
new Person(30, "first2", "last2"),
new Person(40, "first3", "last3"),
new Person(50, "first4", "last4")
};
var list2 = new List<Person>
{
new Person(30, "first2", "last2"),
new Person(50, "first4", "last4")
};
var list3 = list1.Except(list2, new PersonEqualityComparer());
foreach (var person in list3)
{
Console.WriteLine(person);
}
}
}
}