lacoder
lacoder

Reputation: 1323

Custom Validation for Generic Types in c#

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.

Upvotes: 0

Views: 57

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

You can create concatenated hobby strings for each user. This makes it easier to compare the hobbies:

var hobbyStrings = users
    .Select(u => String.Join(",", u.Hobbies.Select(h => h.Name).Order()))
    .ToList();
bool valid = hobbyStrings.Distinct().Count() == hobbyStrings.Count;

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). Order was added in .NET 7.

Upvotes: 1

Related Questions