c# - Best practice for Inline if statement in for loop -
I want to copy the list item to string code. If the listbox item has empty string, then ignore
why I can do this:
foreach (string item in lstModelUsers.Items) {if (string.IsNullOrEmpty ( Items)) continue; other options. Default.model Removal User Add (item); }
But this is not:
foreach (string item is in lstModelUsers.Items) string.IsNullOrEmpty (item)? Continue: Options. Default.model Removal User Add (item);
Although both appear to be the same, inline if
statement generates a syntax error.
What is the best practice?
You can not use it to be the only expressions Accepts your code failing to compile because it can only be used as a statement , not an expression.
The best way to do this is to reject if
expression is not required for you issue
:
Foreach (string item in lstModelUsers.Items) {if String.IsNullOrEmptE (item)) {Options.Default ModelRemoveUsers.Add (item); }}
You can also use where
:
var itemsToAdd = lstModelUsers.Items .Cast & lt; String & gt; () Where (item => String.IsNullOrEmpty (item)); Foreign items (item items in string items) {Options. Default.modelUmUser Add (item); }
If you are lucky, you may also find that there is an AddRange
method in ModelRemoveUsers
Not required at all:
Add for var items = lstModelUsers.Items .Cast & lt; String & gt; (). Where (item => String.IsNullOrEmpty (item)); Options.Default.ModelRemoveUsers.AddRange (itemsToAdd);
Comments
Post a Comment