LINQ Expression> equavalent of .Contains()

前端 未结 2 1976
别那么骄傲
别那么骄傲 2021-02-14 23:32

Has anybody got an idea of how to create a .Contains(string) function using Linq Expressions, or even create a predicate to accomplish this

public static Express         


        
2条回答
  •  暖寄归人
    2021-02-15 00:25

    public static Expression> StringContains(string subString)
    {
        MethodInfo contains = typeof(string).GetMethod("Contains");
        ParameterExpression param = Expression.Parameter(typeof(string), "s");
        var call = Expression.Call(param, contains, Expression.Constant(subString, typeof(string)));
        return Expression.Lambda>(call, param);
    }
    
    ...
    
    // s => s.Contains("hello")
    Expression> predicate = StringContains("hello");
    

    Looking at this many years later, I suddenly realize there's a much simpler approach for this specific example:

    Expression> predicate = s => s.Contains("hello");
    

提交回复
热议问题