18

I'm developing a C# 4.5 app and I need a function to return true for the following comparison:

"bla LéOnAr d/o bla".ComplexContains("leonardo")

In other words, I need string.Compare(str1, str2, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace) to also check for "contains!

Can anyone help?

Divi
  • 7,621
  • 13
  • 47
  • 63
Leonardo
  • 10,737
  • 10
  • 62
  • 155

1 Answers1

42

You could use an appropriate CompareInfo and then CompareInfo.IndexOf(string, string, CompareOptions) and check the result against -1. Sample:

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
        var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
        var options = CompareOptions.IgnoreCase | 
            CompareOptions.IgnoreSymbols |
            CompareOptions.IgnoreNonSpace;

        var haystack = "bla Lé OnAr d/o bla";
        var needle = "leonardo";

        var index = compareInfo.IndexOf(haystack, needle, options);
        Console.WriteLine(index); // 4
    }
}

Or in method form:

private static bool ComplexContains(string source, string value)
{
    var index = CultureInfo.InvariantCulture.CompareInfo.IndexOf
        (source, value, CompareOptions.IgnoreCase | 
         CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace);
    return index != -1;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1 quick question though... how well EF5 transforms this to TSql? im using LINQ here... – Leonardo Mar 02 '13 at 20:47
  • 2
    @Leonardo: I very much doubt that it handles that at all - I wouldn't expect it to. (In future, please give *crucial* details like this in the original question.) – Jon Skeet Mar 02 '13 at 20:50
  • @JonSkeet it's not so crucial... fyi it does work after all... except that the comparison is done a application server... the result sql is almost a "select * from table..." – Leonardo Mar 02 '13 at 20:53
  • 1
    @Leonardo: That suggests you're not actually using that on an `IQueryable` - but if you *did* try doing it on a real queryable type, I'd expect it to fail at execution time. It really is a crucial piece of information - it's like asking about C# and then saying you're actually running Java. *Lots* of stuff which works locally won't work via LINQ. – Jon Skeet Mar 02 '13 at 20:56
  • The method is perfect . Works a treat. – user3569147 May 26 '17 at 22:10
  • This code returns -1 for me, therefore I don't think it's completely accent insensitive. (environment: Xamarin Forms) – adamsfamily Sep 11 '21 at 06:59
  • @adamsfamily: I suspect that may well be more about the Xamarin implementation than about the expected behavior. – Jon Skeet Sep 11 '21 at 10:26