I want to copy Listbox items to StringCollection.
If the listbox items contains empty string then ignore
Why can i do this:
foreach (string item in lstModelUsers.Items)
{
if (string.IsNullOrEmpty(item))
continue;
else
Options.Default.ModelRemoveUsers.Add(item);
}
BUT not this:
foreach (string item in lstModelUsers.Items)
string.IsNullOrEmpty(item)
? continue
: Options.Default.ModelRemoveUsers.Add(item);
Although both appear equal, the inline if statement generates a syntax error.
What is the best practice?
You can’t use the conditional operator like that. It only accepts expressions as its operands. Your code fails to compile because
continuecan only be used as a statement, not an expression.A better approach is to negate the
ifexpression so that you don’t need thecontinue:You could also use
Where:If you are lucky, you may even find that
ModelRemoveUsershas anAddRangemethod, then you don’t need the loop at all: