.net 带子字符串的LINQ表达式树

6tqwzwtp  于 2022-12-14  发布在  .NET
关注(0)|答案(1)|浏览(94)

我想创建SQL LINQ表达式如下:

.Where(product => product.name.Substring(3,5).Contains("ma")

有人能帮我创造这个表情吗?

Expression.PropertyOrField(body, "name.Substring(3,5)");

我尝试了,但出现错误
子字符串(3,5)不是类型“System.String”的成员

r3i60tvu

r3i60tvu1#

假设我们有一个类Product

public class Product
{
    public string name;
}

然后可以将Expression创建为:

Expression<Func<Product, bool>> expression = product => product.name.Substring(3, 5).Contains("ma");
Console.WriteLine(expression); // product => product.name.Substring(3, 5).Contains("ma")

如果需要手动创建表达式,请考虑以下事项:

var parameter = Expression.Parameter(typeof(Product), "product");
var expression = Expression.Lambda<Func<Product, bool>>(
    Expression.Call(
        Expression.Call(
            Expression.PropertyOrField(parameter, "name"),
            typeof(string).GetMethod("Substring", new[] { typeof(int), typeof(int) }),
            Expression.Constant(3, typeof(int)),
            Expression.Constant(5, typeof(int))),
        typeof(string).GetMethod("Contains", new[] { typeof(string) }),
        Expression.Constant("ma", typeof(string))),
    parameter);
Console.WriteLine(expression); // product => product.name.Substring(3, 5).Contains("ma")

霍普对你有帮助。

相关问题