Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for string.Contains(string, StringComparison) in .Net Standard 2.0

Consider the following codes :

public static IQueryable<T> WhereDynamic<T>(this IQueryable<T> sourceList, string query)
{
    if (string.IsNullOrEmpty(query))
    {
        return sourceList;
    }

    try
    {
        var properties = typeof(T).GetProperties()
            .Where(x => x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);

        //Expression
        sourceList = sourceList.Where(c =>
            properties.Any(p => p.GetValue(c) != null && p.GetValue(c).ToString()
                .Contains(query, StringComparison.InvariantCultureIgnoreCase)));
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    return sourceList;
}

I have created a project of type .Net Standard 2.0 and I want to use the above code in it. But the problem is that it is not possible to use this overload:

.Contains method (query, StringComparison.InvariantCultureIgnoreCase)

It does not exist. While in a .NET Core project, there is no problem. Do you have a solution or alternative to that overload of the Contains() method?

like image 331
farshid azizi Avatar asked Dec 31 '22 22:12

farshid azizi


2 Answers

You can use IndexOf with a StringComparison, and then check if the result is non-negative:

string text = "BAR";
bool result = text.IndexOf("ba", StringComparison.InvariantCultureIgnoreCase) >= 0;

It's possible that there will be some really niche corner cases (e.g. with a zero-width non-joiner character) where they'll give a different result, but I'd expect them to be equivalent in almost all cases. Having said that, the .NET Core code on GitHub suggests that Contains is implemented in exactly this way anyway.

like image 142
Jon Skeet Avatar answered Jan 29 '23 18:01

Jon Skeet


Jon has the right answer, I just need to verify his answer, and Contains implementation uses IndexOf in .NET Framework. What you can do is to add extension to whatever method that is not included in .NET Standard.

for your Contains the extension would like :

public static bool Contains(this string str, string value,  StringComparison comparison)
{
    return str.IndexOf(value, comparison) >= 0;
}

You can do the same for the reset. If you need more implementations details, you could checkout Microsoft Reference which would give you a good understanding on the .NET underlying implementation.

like image 27
iSR5 Avatar answered Jan 29 '23 19:01

iSR5