I have an object with multiple strings.
Is there a way to check if one of the values is null or all values are set?
Or do I have to do it like this:
if (!string.IsNullOrWhiteSpace(object.string1) || !string.IsNullOrWhiteSpace(object.string2) || !string.IsNullOrWhiteSpace(object.string3))
{
}
CodePudding user response:
You can gather all your strings into an array and then run .Any()
method:
if (new[] { obj.string1, obj.string2, obj.string3 }.Any(string.IsNullOrWhiteSpace))
{
}
Alternatively you can use reflection (which will affect your code's performance), to scan all the strings of your object and check your condition:
var anyEmpty = obj.GetType().GetProperties()
.Any(x => x.PropertyType == typeof(string)
&& string.IsNullOrWhiteSpace(x.GetValue(obj) as string));
CodePudding user response:
You can use a for loop to iterate trough all strings and check if they are blank or empty.
EDIT: You probably have to add all the strings into an array or a list, because they all have different names like string1, string2 and string3
CodePudding user response:
If you do this a lot, you could write a method to check it:
public static class Ensure
{
public static bool NoneNullOrWhitespace(params string?[] items)
{
return !items.Any(string.IsNullOrWhiteSpace);
}
}
Which for your case you would call like this:
if (Ensure.NoneNullOrWhitespace(object.string1, object.string2, object.string3))
{
...
}
CodePudding user response:
If it's an option for you to define a class for your objects, you could let the class itself handle the "all strings not null or whitespace"-check:
public class MyObject
{
public string String1 { get; set; }
public string String2 { get; set; }
public string String3 { get; set; }
public bool StringsAreNotNullOrWhiteSpace => !Strings.Any(string.IsNullOrWhiteSpace);
private string[] Strings => new[] { String1, String2, String3 };
}
and use it like this:
var myObject = new MyObject();
//Populate myObject
if (myObject.StringsAreNotNullOrWhiteSpace)
{
//Add myObject to list
}
(The implementation of StringsAreNotNullOrWhiteSpace
is basically what @mickl did in their first suggestion, but returning the opposite bool value.)