tags:

views:

130

answers:

4

I have a method right now that loops through a list of business objects name Properties has a Serial # or not. If I find a Serial #, I exit the loop and return true, otherwise I return false.

Code is as follows:

  public bool HasSerialNumber()
    {
        if (this.Properties != null && this.Properties.Count > 0)
        {
            foreach (var property in Properties)
            {
                if (!string.IsNullOrEmpty(property.SerialNumber))
                    return true;
            }
        }

        return false;
    }

Is there a better LINQ approach to this?

I have the following in mind:

return Properties.Where(x => !string.IsNullOrEmpty(x.SerialNumber)).ToList().Count > 0;

Is there a better/faster method for checking for non empty string?

+11  A: 

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.

ŁukaszW.pl
+1. Apart from better communicating your intent, the added bonus of using `Any()` is that the underlying list will only be iterated until a property with serial number is found. If you use Count() or ToList(), the complete list must be evaluated, so you lose some performance. Of course, it will not make a big difference in this case, but still.
jeroenh
+3  A: 

This should do the trick:

return Properties.Any(x => !string.IsNullOrEmpty(x.SerialNumber));
veggerby
+9  A: 

Check out IEnumerable<T>.Any():

public bool HasSerialNumber()
{
    if(this.Properties != null)
        return Properties.Any(p => !string.IsNullOrEmpty(p.SerialNumer));
    return false;
}
Justin Niessner
+6  A: 

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));
Ryan Brunner