Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build Expression Equals on string

The code below works with StartsWith and Contains but when I tried Equals I get this exception : More than one method 'Equals' on type 'System.String' is compatible with the supplied arguments.

To resume, the CreatePredicate can build 3 types of predicate but only the Equals does not work :

  • AList.Where(x => x.MyField.StartsWith("ValueToSearch")); //OK
  • AList.Where(x => x.MyField.Contains("ValueToSearch")); //OK
  • AList.Where(x => x.MyField.Equals("ValueToSearch")); //Not OK

..

public enum TypeSearch
        {
            StartsWith = 1,
            Contains = 2,
            Equals = 3
        }

    private static Expression<Func<T, bool>> CreatePredicate<T>(string member, object value, TypeSearch type)
    {
        var p = System.Linq.Expressions.Expression.Parameter(typeof(T));
        System.Linq.Expressions.Expression body = p;
        foreach (var subMember in member.Split('.'))
        {
            body = System.Linq.Expressions.Expression.PropertyOrField(body, subMember);
        }

        var res = System.Linq.Expressions.Expression.Lambda<Func<T, bool>>(
                System.Linq.Expressions.Expression.Call(
                    System.Linq.Expressions.Expression.Call(
                        body,
                        "ToUpper", null),
                    type.ToString(), null,
                    System.Linq.Expressions.Expression.Constant(value.ToString().ToUpper())
                ), p);

        return res;
    }
like image 306
Kris-I Avatar asked Oct 26 '25 15:10

Kris-I


1 Answers

As the error message explains, there is more than one Equals method defined on the string type - Equals(object) and Equals(string). Since you are only using the name to locate the method you want, the match is ambiguous.

One solution is to pass the MethodInfo for the method to Expression.Call e.g.

MethodInfo equalsMethod = typeof(string).GetMethod("Equals", new[] { typeof(string) });
Expression.Call(instanceExpr, equalsMethod, Expression.Constant(value.ToString().ToUpper()));
like image 154
Lee Avatar answered Oct 29 '25 03:10

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!