Reputation: 1901
I have 3 properties (for sake of simplicity 3 variables)
Method FillOrNotFill
illustrates that strings a
, b
, c
can be empty, not empty or null.
I need to validate a case that only one string must be not empty and not null, where the others must be empty or null.
I can do it with multiple conditions (like in those multiple if's), but Im looking for some more elegant solution.
string x = "someValue"
string a = FillOrNotFill(x);
string b = FillOrNotFill(x);
string c = FillOrNotFill(x);
//sample of multiple if's
if((!string.IsNullOrWhiteSpace(payload.a) && string.IsNullOrWhiteSpace(payload.b) && string.IsNullOrWhiteSpace(payload.c))
|| (!string.IsNullOrWhiteSpace(payload.b) && string.IsNullOrWhiteSpace(payload.a) && string.IsNullOrWhiteSpace(payload.c)
|| (!string.IsNullOrWhiteSpace(payload.c) && string.IsNullOrWhiteSpace(payload.b) && string.IsNullOrWhiteSpace(payload.a)
)))
{
//valid!
}
Upvotes: 3
Views: 1338
Reputation: 460208
You could put them into a colllection, then its easy:
string[] all = {a, b, c};
bool result = all.Count(s => !string.IsNullOrWhiteSpace(s)) == 1;
If there were thousands you could make it more efficient in this way:
bool result = all.Where(s => !string.IsNullOrWhiteSpace(s)).Take(2).Count() == 1;
Upvotes: 5