LINQ approach to this code

I have a method right now that iterates over a list of business objects (property properties) to check if the property is a SerialNumberserial number or not. If I find the serial number, I exit the loop and return true, otherwise return false.

The 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 mean the following:

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

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

+3
source share
4 answers

You can use Anyinstead of checking if the counter is larger.

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

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

+12
source

Departure IEnumerable<T>.Any():

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

, string.IsNullOrEmpty(), , , - 2 - ToList() Count().

What you do there iterates through each element, converting it to a list (creating a list and adding elements to the process, and then repeating each element in the list to calculate how many there are - all to check, one value is empty.

You can use the method Anyto find if one item matches certain criteria, for example:

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

This should do the trick:

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

Source: https://habr.com/ru/post/1758920/


All Articles