开发者

LINQ approach to this code

开发者 https://www.devze.com 2023-01-11 11:54 出处:网络
I have a method right now that loops through a list of business objects (property Properties) to test if property SerialNumber is a serial number or not.If I find a serial number, I exit the loop and

I have a method right now that loops through a list of business objects (property Properties) to test if property SerialNumber is a serial number or not. If I find a serial number, 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开发者_JAVA技巧 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?


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.


Check out IEnumerable<T>.Any():

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


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


This should do the trick:

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

精彩评论

暂无评论...
验证码 换一张
取 消