ASP.NET C# – Case-insensitive String.Contains Helper & Extension Method How to perform a case-insensitive String.Contains search in ASP.NET C# with culture-based comparison support

ASP.NET C# - Case-insensitive String.Contains Helper & Extension Method

If you stumbled upon this post it probably means that you’re trying to use the   method in a C# application in a case-insensitive way: as a matter of fact, there isn’t a built-in overload method accepting a   options object, hence is not possible to do that.

To work around it, most programmers just do something like this:

However, I prefer to use the following extension method, which does the same thing in a much cleaner way and also with better performances:

The method can be used either as standard method by implementing it in a static class or also as an extension method, in the following way:

Potential issue with different Cultures

This solution will work fine for english and latin-based cultures, where the upper-case and lower-case rules works the way we’re used to. That’s not true for some specific Cultures: think about the Turkish language, where the upper-case version of the ‘i’ letter is the unfamiliar character ‘İ’… Meaning that the strings “ICON” and “icon”, which are the same word in English, are treated in Turkish as they are two different word.

If you’re dealing with these kind of cultures, the above method won’t work properly, unless that culture is the exact same one the application is running with – that being the case, you could just use   and be done with. If that’s not the case, you should fetch the   object describing the language that the text you need to compare and use the   method provided by that class instead, in the following way:

Meaning that our extension method should be something like this:

The exact same logic also applies to all other string-comparison based methods, such as  ,  ,   /  , and so on.

That’s about it: happy coding!

 

 

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.