score:12

Accepted answer

You can use Any instead of checking if the count is greater than zero.

return Properties.Any(x => !string.IsNullOrEmpty(x.SerialNumber))

and of course your Properties.Count > 0 check is redundant.

score:3

This should do the trick:

return Properties.Any(x => !string.IsNullOrEmpty(x.SerialNumber));

score:9

Check out IEnumerable<T>.Any():

public bool HasSerialNumber()
{
    if(this.Properties != null)
        return Properties.Any(p => !string.IsNullOrEmpty(p.SerialNumer));
    return false;
}

score:6

I don't think you'll improve particularly on the performance of string.IsNullOrEmpty(), but one pitfall you should be avoiding is the last 2 calls on your query - specifically ToList() and Count().

What you are doing there is iterating through every element, converting it to a list (creating a list and adding items in the process, and then iterating through every element on the list to count how many there are - all to check if a single value is empty.

You can use the Any method to find if a single element matches certain criteria, like so:

return Properties.Any(x => !string.IsNullOrEmpty(x.SerialNumber));

Related Articles