Richard
Richard

Reputation: 588

How to use Ternary operator when the expression is only true?

I have a problem when wanting to use the ternary operator in a ForEach extension. My code is as follows:

List<string> lstText = new List<string>();
lstComboBox.ForEach(x => !String.IsNullOrWhiteSpace(x.Text) ? lstText.Add(x.Text));

I need to use the ternary operator to validate that there is a text comboBox and then save it to the list, if you do not find something, does nothing.

Upvotes: 0

Views: 286

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660573

I need to use the ternary operator to validate that there is a text comboBox and then save it to the list, if you do not find something, does nothing.

Don't do that. It's terrible style, hard to reason about, and contrary to common practice.

Do this:

var result = comboBox
             .Select(comboBoxItem => comboBoxItem.Text)
             .Where(text => !String.IsNullOrWhiteSpace(text))
             .ToList();

You have three logical operations: get the text out of the combo box, filter out the blank text, create a list. This program very clearly does those three things. Don't mess around with loops and ternaries and adding things to lists unless you need to; write the program at the level that expresses what you are trying to do and not how you are doing it.

Upvotes: 12

Related Questions