I need to compare two hashsets that are of the same type, but have differing values for only some properties. I essentially need a more specific ExceptWith.
I've tried using ExceptWith but that doesn't allow you to specify a property to compare on, as far as I know.
We should pretend that I cannot add or remove any properties to the Person class.
class Program
{
private class Person
{
public string Name { get; set; }
public string Id { get; set; }
}
static void Main(string[] args)
{
var people1 = new[]
{
new Person
{
Name = "Amos",
Id = "123"
},
new Person
{
Name = "Brian",
Id = "234"
},
new Person
{
Name = "Chris",
Id = "345"
},
new Person
{
Name = "Dan",
Id = "456"
}
};
var people2 = new[]
{
new Person
{
Name = "Amos",
Id = "098"
},
new Person
{
Name = "Dan",
Id = "987"
}
};
var hash1 = new HashSet<Person>(people1);
var hash2 = new HashSet<Person>(people2);
var hash3 = new HashSet<Person>(); // where hash3 is hash1 without the objects from hash2 solely based on matching names, not caring about Id matching
foreach (var item in hash3) // should print out Brian, Chris
{
Console.WriteLine($"{item.Name}");
}
}
}