Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# LINQ How to Check if any element in a String array contains 'Error' or IsNullOrEmpty

I have a statement that checks if any element in a string array contains Error text value.

bool containsError = myStringArray.Contains("Error", StringComparer.InvariantCultureIgnoreCase);

How can I add another condition to also check if any element isNullOrEmpty?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way is to add a condition with Any():

bool containsErrorOrEmptyElement = myStringArray.Contains("Error", StringComparer.InvariantCultureIgnoreCase)
                                   || myStringArray.Any(s => string.IsNullOrWhiteSpace(s));

I used string.IsNullOrWhiteSpace after assuming it better fits your requirements; you can also use string.IsNullOrEmpty instead.

You can also use LINQ’s Any for both conditions, by using the string.Equals method for case-insensitive comparison:

bool containsError = myStringArray.Any(s => string.IsNullOrWhiteSpace(s)
    || s.Equals("Error", StringComparison.InvariantCultureIgnoreCase));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading