Efficiently Checking if a String Does Not Contain Multiple Substrings in C#

Dec 05, 2025 · Programming · 9 views · 7.8

Keywords: C# | string | Contains | LINQ | culture-sensitivity

Abstract: This article explores methods to determine when a string does not contain two or more specified substrings in C#, focusing on the use of collections and LINQ for efficient and culture-aware searches. It provides code examples and comparisons with alternative approaches.

Introduction

In C#, a common task is to determine if a string does not contain multiple specified substrings. For instance, given strings like "pineapple" and "mango", we might want to check if a comparison string such as "The wheels on the bus go round and round" contains neither of them.

Core Solution Using Collections and LINQ

The most efficient approach is to store the substrings in a collection and use LINQ's Any method to perform the check. This method allows for concise and readable code.

Here's a basic implementation:

var searchFor = new List<string> { "pineapple", "mango" };
string compareString = "The wheels on the bus go round and round";
bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));

If containsAnySearchString is true, it means the compareString contains at least one of the substrings. To check if it does not contain any, you can negate the result: !containsAnySearchString.

Handling Culture Sensitivity

For case-insensitive or culture-aware searches, use the IndexOf method with appropriate StringComparison options:

bool containsAnySearchString = searchFor.Any(word => 
    compareString.IndexOf(word, StringComparison.InvariantCultureIgnoreCase) >= 0);

This ensures that the search is not affected by cultural differences in string comparison.

Alternative Method

As a supplementary reference, a simpler method for checking two strings is using the logical AND operator:

if (!(compareString.Contains("pineapple") && compareString.Contains("mango")))
{
    // Code when both strings are not contained
}

However, this approach is less scalable for multiple substrings and does not easily handle culture sensitivity.

Conclusion

To efficiently check if a string does not contain multiple substrings in C#, leveraging collections and LINQ's Any method is recommended. It provides flexibility, scalability, and options for culture-aware searches, making it the preferred solution for most scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.