对于给定的搜索标签过滤器,预期结果是一个表达式,该表达式表示在给定的标签ID列表中具有所有标签的实体。
Lambda可能表示为:
class Tag
{
public long TagId { get; set; }
}
class Taggable
{
ICollection<Tag> Tags { get; set; }
}
...
IEnumerable<long> searchTags = new List<long>() { 1, 2, 3 };
Func<Taggable, bool> filter = taggable => searchTags.All(qtag => taggable.Tags.Any(tag => tag.TagId == qtag));
尝试将其表示为表达式树失败:
var tagParam = Expression.Parameter(typeof(Tag), "tag");
var taggableParam = Expression.Parameter(typeof(Taggable), "taggable");
MemberExpression tagsProperty = Expression.Property(taggableParam, "Tags");
ConstantExpression searchTagsConstant = Expression.Constant(searchTags);
var containsCall = Expression.Call(
typeof(Enumerable), "Contains",
new[] { typeof(long) },
searchTagsConstant,
Expression.Property(tagParam, "TagID")
);
var anyCall = Expression.Call(
typeof(Enumerable), "Any",
new[] { typeof(Tag) },
tagsProperty,
Expression.Lambda(containsCall, tagParam)
);
// FAILS HERE
var allCall = Expression.Call(
typeof(Enumerable), "All",
new[] { typeof(long) },
searchTagsConstant,
anyCall
);
类型'System.Linq.Enumerable'上的通用方法'All'不兼容 与提供的类型参数和参数。没有类型参数 如果该方法是非泛型的,则应提供。
有人认为它会起作用,因为Enumerable.All<TSource, Func<TSource, bool>>
和searchTagsConstant
应该使anyCall
满意?
答案 0 :(得分:5)
t被认为可以正常工作,因为
Enumerable.All<TSource, Func<TSource, bool>>
和searchTagsConstant
应该满足anyCall
不。 anyCall
不是lambda表达式(Func<TSource, bool>
),只是该表达式的潜在 body 。
让我们从目标开始:
IEnumerable<long> searchTags = new List<long>() { 1, 2, 3 };
Expression<Func<Taggable, bool>> lambda =
taggable => searchTags.All(searchTag => taggable.Tags.Any(tag => tag.TagId == searchTag));
学习如何构建表达式树的最简单方法是在编译时创建示例表达式,然后通过一些反编译器检查生成的代码,或者在运行时通过调试器检查生成的代码。
无论如何,请注意,上面的表达式具有3个lambda参数,而在尝试中只有2个。此外,没有Contains
调用,不确定为什么要放在其中。
构建上面的表达式可以像这样:
var taggable = Expression.Parameter(typeof(Taggable), "taggable");
var tag = Expression.Parameter(typeof(Tag), "tag");
var searchTag = Expression.Parameter(typeof(long), "searchTag");
// tag.TagId == searchTag
var anyCondition = Expression.Equal(
Expression.Property(tag, "TagId"),
searchTag);
// taggable.Tags.Any(tag => tag.TagId == searchTag)
var anyCall = Expression.Call(
typeof(Enumerable), nameof(Enumerable.Any), new[] { typeof(Tag) },
Expression.Property(taggable, "Tags"), Expression.Lambda(anyCondition, tag));
// searchTags.All(searchTag => taggable.Tags.Any(tag => tag.TagId == searchTag))
var allCall = Expression.Call(
typeof(Enumerable), nameof(Enumerable.All), new[] { typeof(long) },
Expression.Constant(searchTags), Expression.Lambda(anyCall, searchTag));
// taggable => searchTags.All(searchTag => taggable.Tags.Any(tag => tag.TagId == searchTag))
var lambda = Expression.Lambda(allCall, taggable);