I have this method, this works as expected, it does not insert <string, value> if string is empty, however I have an issue where the string does't always exists. I want to avoid appending anything if string does not exists.
public static class StringBuilderExtension
{
public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, string prefix)
where TValue : class
{
if (value != null)
{
sb.Append(prefix + value);
}
}
}
The issue is I am always passing the string key
sb.AppendIfNotNull(" width=\"", component.style.width + "\"");
This will appear as width="" as I physically appended the string. How can I stop this from happening.
I can stop it from appear if I wrap it around an if statement
if (item.width!= null)
{
sb.AppendIfNotNull(" width=\"", item.width + "\"");
}
Object example. Property might exists in one object but might not on the next. e.g. Do not append color if it does not exists:
{
'id': 'Test',
'type': 'Text',
'style': {
'color': 'black'
'textSize': '12'
}
},
{
'id': 'Test',
'type': 'Text',
'style': {
'textSize': '12'
}
}
string(key)? I don't see akeyanywhere. It sounds like you just don't want to append the value if it's an empty string. You could just dovar valueToAppend = value?.ToString();and thenif(!string.IsNullOrEmpty(valueToAppend)) sb,Append(prefix + valueToAppend);XElementmight throw away all of your problems. Are you eventually generating XML? If that is the case, it might be interesting to look at other ways to handle that, than using a stringbuilder