Use C # extension method as predicate in linq query

I applied the extension method to normalize the line described in this post: LINQ Where Ignore Accentuation and Case

This method works like a charm if I do things like this:

employee.AsQueryable().Where(t=>t.Text.ToLower().RemoveDiacritics().Contains("ced"));

Now I want to use it more universally, creating a dynamic predicate of the where clause.

var values = filters.Select(f => f.Value is string && f.IgnoreAccent
                               ?((string)f.Value).RemoveDiacritics()
                               :f.Value).ToArray();

// Create a predicate expression
string predicate = filter.ToExpression(filters);

// Use the Where method of Dynamic Linq to filter the data
queryable = queryable.Where(predicate, values);

The predicate will look like this:

(Text.ToLower().RemoveDiacritics().Contains(@0))

For an unknown reason, I received the following error message during execution:

No applicable method "RemoveDiacritics" exists in type "String"

But this method works fine if I use it elsewhere.

Any ideas what is wrong here?

Note that it ToLower()works like a charm in this situation.

Thanks in advance for your help!

EDIT

:

public static class StringExtension
{
    public static string RemoveDiacritics(this String s)
    {
        String normalizedString = s.Normalize(NormalizationForm.FormD);
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < normalizedString.Length; i++)
        {
            Char c = normalizedString[i];

            if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                stringBuilder.Append(c);
        }

        return stringBuilder.ToString();
    }
}
+4
2

Linq . , Dynamic Linq , . Linq .

, :

var values = filters.Select(f => f.Value is string && f.IgnoreAccent
                           ?StringExtensions.RemoveDiacritics((string)f.Value)
                           :f.Value).ToArray();
+2
employee.AsQueryable().Where(t=>t.Text.ToLower().RemoveDiacritics().Contains("ced"));

employee.AsQueryable().Where(t=>t.Text.Equals("ced", StringComparison.OrdinalIgnoreCase));

.

0

Source: https://habr.com/ru/post/1614491/


All Articles