.net-如何在C#中创建一个表达式树来表示'String.Contains(“ term”)'?

我刚刚开始使用表达式树,所以我希望这是有道理的。 我试图创建一个表达式树来表示:

t => t.SomeProperty.Contains("stringValue");

到目前为止,我已经:

    private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue)
    {
        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameter, propertyName);
        var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)
        ...
        return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this
    }

我只是不知道如何引用String.Contains()方法。

帮助表示赞赏。

flesh asked 2019-11-07T18:42:19Z
4个解决方案
130 votes

就像是:

class Foo
{
    public string Bar { get; set; }
}
static void Main()
{
    var lambda = GetExpression<Foo>("Bar", "abc");
    Foo foo = new Foo { Bar = "aabca" };
    bool test = lambda.Compile()(foo);
}
static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
    var parameterExp = Expression.Parameter(typeof(T), "type");
    var propertyExp = Expression.Property(parameterExp, propertyName);
    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var someValue = Expression.Constant(propertyValue, typeof(string));
    var containsMethodExp = Expression.Call(propertyExp, method, someValue);

    return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}

您可能会发现这很有帮助。

Marc Gravell answered 2019-11-07T18:42:36Z
7 votes

这个怎么样:

Expression<Func<string, string, bool>> expFunc = (name, value) => name.Contains(value);

在客户端代码中:

    bool result = expFunc.Compile()("FooBar", "Foo");   //result true
    result = expFunc.Compile()("FooBar", "Boo");        //result false
Abhijeet Patel answered 2019-11-07T18:43:01Z
7 votes

要执行类似的搜索:

ef.Entities.Where(entity => arr.Contains(entity.Name)).ToArray();

跟踪字符串将是:

SELECT .... From Entities ... Where Name In ("abc", "def", "qaz")

我使用下面创建的方法:

ef.Entities.Where(ContainsPredicate<Entity, string>(arr, "Name")).ToArray();

public Expression<Func<TEntity, bool>> ContainsPredicate<TEntity, T>(T[] arr, string fieldname) where TEntity : class {
  ParameterExpression entity = Expression.Parameter(typeof(TEntity), "entity");
  MemberExpression member = Expression.Property(entity, fieldname);

  var containsMethods = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
  .Where(m => m.Name == "Contains");
  MethodInfo method = null;
  foreach (var m in containsMethods) {
    if (m.GetParameters().Count() == 2) {
      method = m;
      break;
    }
  }
  method = method.MakeGenericMethod(member.Type);
  var exprContains = Expression.Call(method, new Expression[] { Expression.Constant(arr), member });
  return Expression.Lambda<Func<TEntity, bool>>(exprContains, entity);
}
Leng Weh Seng answered 2019-11-07T18:43:37Z
0 votes

这是创建string.Contains的表达式树的方法。

var method = typeof(Enumerable)
    .GetRuntimeMethods()
    .Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2);
var containsMethod = method.MakeGenericMethod(typeof(string));
var doesContain = Expression
.Call(containsMethod, Expression.Constant(criteria.ToArray()),
 Expression.Property(p, "MyParam"));

实际使用情况为[https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs]

Xavier John answered 2019-11-07T18:44:07Z
translate from https://stackoverflow.com:/questions/278684/how-do-i-create-an-expression-tree-to-represent-string-containsterm-in-c