Expression.Lambda 和在运行时生成查询,嵌套 属性 “Where” 示例
Expression.Lambda and query generation at runtime, nested property “Where” example
我在有关为 Where 查询构建表达式树的问题上找到了非常好的答案。
Expression.Lambda and query generation at runtime, simplest "Where" example
谁能帮我看看这个例子如何在嵌套 属性 的场景中实现。我的意思是:
var result = query.Where(item => item.Name == "Soap")
有了那个解决方案:
var item = Expression.Parameter(typeof(Item), "item");
var prop = Expression.Property(item, "Name");
var soap = Expression.Constant("Soap");
var equal = Expression.Equal(prop, soap);
var lambda = Expression.Lambda<Func<Item, bool>>(equal, item);
var result = queryableData.Where(lambda);
如何为以下内容构建树?
var result = query.Where(item => item.Data.Name == "Soap").
(此答案最初由问题中的 OP 发布。)
问题可以通过以下方式解决:
var item = Expression.Parameter(typeof(Item), "item");
var dataExpr = Expression.Property(item, "Data");
var prop = Expression.Property(dataExpr, "Name");
var soap = Expression.Constant("Soap");
var equal = Expression.Equal(prop, soap);
var lambda = Expression.Lambda<Func<Item, bool>>(equal, item);
var result = queryableData.Where(lambda);
这与上面发布的答案相同,但我发现它在可视化表达式树方面更具可读性:
var parameterItem = Expression.Parameter(typeof(Item), "item");
var lambda = Expression.Lambda<Func<Item, bool>>(
Expression.Equal(
Expression.Property(
Expression.Property(
parameterItem,
"Data"
),
"Name"
),
Expression.Constant("Soap")
),
parameterItem
);
var result = queryableData.Where(lambda);
我在有关为 Where 查询构建表达式树的问题上找到了非常好的答案。
Expression.Lambda and query generation at runtime, simplest "Where" example
谁能帮我看看这个例子如何在嵌套 属性 的场景中实现。我的意思是:
var result = query.Where(item => item.Name == "Soap")
有了那个解决方案:
var item = Expression.Parameter(typeof(Item), "item");
var prop = Expression.Property(item, "Name");
var soap = Expression.Constant("Soap");
var equal = Expression.Equal(prop, soap);
var lambda = Expression.Lambda<Func<Item, bool>>(equal, item);
var result = queryableData.Where(lambda);
如何为以下内容构建树?
var result = query.Where(item => item.Data.Name == "Soap").
(此答案最初由问题中的 OP 发布。)
问题可以通过以下方式解决:
var item = Expression.Parameter(typeof(Item), "item");
var dataExpr = Expression.Property(item, "Data");
var prop = Expression.Property(dataExpr, "Name");
var soap = Expression.Constant("Soap");
var equal = Expression.Equal(prop, soap);
var lambda = Expression.Lambda<Func<Item, bool>>(equal, item);
var result = queryableData.Where(lambda);
这与上面发布的答案相同,但我发现它在可视化表达式树方面更具可读性:
var parameterItem = Expression.Parameter(typeof(Item), "item");
var lambda = Expression.Lambda<Func<Item, bool>>(
Expression.Equal(
Expression.Property(
Expression.Property(
parameterItem,
"Data"
),
"Name"
),
Expression.Constant("Soap")
),
parameterItem
);
var result = queryableData.Where(lambda);