Given entity types as below
List<User> users = new List<User>
{
new User
{
Name = "John",
Hobbies = new List<Hobby>
{
new Hobby { Id = 1, Name = "Reading" },
new Hobby { Id = 2, Name = "Gaming" }
}
},
new User
{
Name = "Alice",
Hobbies = new List<Hobby>
{
new Hobby { Id = 3, Name = "Photography" },
new Hobby { Id = 4, Name = "Hiking" }
}
},
new User
{
Name = "Bob",
Hobbies = new List<Hobby>
{
new Hobby { Id = 5, Name = "Photography" },
new Hobby { Id = 6, Name = "Hiking" }
}
},
new User
{
Name = "John",
Hobbies = new List<Hobby>
{
new Hobby { Id = 7, Name = "Gaming" },
new Hobby { Id = 8, Name = "Reading" }
}
}
};
I want to validate that the list of users do not have duplicated hobby sets.For example, Photography and Hiking should be a duplicate hobby set thus raising an exception.How can I achieve a custom Validator so that the hobby sets are unique for each user?
Basically what Ive done in the interim is to convert the object types to a string and then group the data.I've also tried employing custom validation using the IValidateableObject against the class to no avail.
You can create concatenated hobby strings for each user. This makes it easier to compare the hobbies:
This assumes that the order of the hobbies doesn't matter. If the order matters, simply remove the
.Order()call.Note: in older BCL versions you will have to replace
.Order()(if you want to keep it) with.OrderBy(h => h).Orderwas added in .NET 7.