Reputation: 3097
I have a pretty long and unwieldy method which takes in an object as a parameter, then checks every property against the same criteria (== "random") and performs a specific action against the property.
public void CreateRegistration(UserGroup user, int mobileLength, int passwordLength, int questionLength) {
if (user.Title == "random") {
title.ClickDropdown();
} else {
WebElementExtensions.ClickDropdown(title,user.Title);
}
if (user.Firstname == "random") {
firstName.SendKeys(GenerateData.GenerateRandomName());
} else {
firstName.SendKeys(user.Firstname);
}
if (user.Middlename == "random") {
middleName.SendKeys(GenerateData.GenerateRandomName());
} else {
firstName.SendKeys(user.Middlename);
}
etc....
Is it possible to somehow check all my properties against the same criteria together, then reduce my code so all the actions on the individual properties are within the same code block? so one code block for is = random and one for else.
Many thanks,
Upvotes: 1
Views: 1668
Reputation: 39946
I prefer to use LINQ for this purpose usually:
private bool CheckAllProperties(UserGroup instance)
{
return instance.GetType().GetProperties()
.Where(c => c.GetValue(instance) is string)
.Select(c => (string)c.GetValue(instance))
.All(c => c== "random");
}
And then:
if (CheckAllProperties(user))
{
}
Upvotes: 4