Domanda

I have a 'search page' where it is required that at least one textbox has some input. The following method verifies this like so:

    if (!String.IsNullOrEmpty(txtNome.Text))
    {
        return true;
    }
    if (!String.IsNullOrEmpty(txtEndereco.Text))
    {
        return true;
    }
    if (!String.IsNullOrEmpty(txtCidade.Text))
    {
        return true;
    }
    if (!String.IsNullOrEmpty(txtCEP.Text))
    {
        return true;
    }

    return false;

There hasn't been any problems with the results from this method. My question is related to performance: Is there a better way to make this check? One possible alternative I've thought of:

string X = String.Concat(txtNome.Text,...,txtCEP.Text)
if(!String.IsNullOrEmpty(X))
{
    return true;
} 

I think that using the if-return pattern is better when the first field isn't empty, but for other use-cases, using String.Concat is better.

Could someone let me know which way is better and why? Is there another, even better way?

È stato utile?

Soluzione

If all the controls are of the same type, you could put all the controls you want to check in an array then use Linq's Any extension method:

return new[] { txtNome, txtEndereco, txtCidade, txtCEP }
    .Any(x => !String.IsNullOrEmpty(x.Text));

Or alternatively, if not all of the controls are of the same type, create an array of strings:

return new[] { txtNome.Text, txtEndereco.Text, txtCidade.Text, txtCEP.Text }
    .Any(x => !String.IsNullOrEmpty(x));

The performance difference between this and a plain old if-else-block will be negligible.

Altri suggerimenti

From a pure performance standpoint, the only way your original method could get more efficient is if you wrote the checks in order of the most used to least used.

But simple operations like comparing values are near-instantaneous for even old, outdated technology. Trying to optimize here is a genuine waste of your time. Instead focus on learning ways to write code quicker and more concisely, so when you re-visit the code in the future, it will be much easier to understand and modify. p.s.w.g's answer shows how you can leverage linq; I'd recommend trying that out.

On a side note, I'd recommend that you instead of String.IsNullOrEmpty(), you use String.IsNullOrWhiteSpace(). Again, it does requires a slight additional performance overhead, but it is much more useful.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top