T,T,BOOL>从Func键<获取; + T实例表达式来; Func键< T,BOOL>> [英] Getting from Func<T, T, bool> + T instance to Expression<Func<T, bool>>
问题描述
如果我有一个 Func键< T,T,BOOL>
,告诉我如何在两个TS比较如
If I have a Func<T, T, bool>
that tells me how to compare two Ts as in
var comparer = (a, b) =>
a.IdPart1 == b.IdPart1 && a.IdPart2 == b.IdPart2;
和我想用这个和T的具体实例来创建表达式来; Func键< T,BOOL>>
用作谓语为凡(),如
And I want to use this and a concrete instance of T to create a Expression<Func<T, bool>>
to be used as a predicate for Where() such as
T instance = GetSomeT();
TRepository.GetAll().Where(x =>
x.IdPart1 == instance.IdPart1 && x.IdPart2 == instance.IdPart2);
但当然,动态的,这样我可以代替写
but of course dynamically so that I could instead write
var predicate = something depending on comparer and instance;
TRepository.GetAll().Where(predicate);
这可能吗?
Is it possible?
更酷是,如果我可以动态创建谓词只是在T与KeyAttribute和和
之间的所有属性之间的平等,这样我就不需要比较器,只需T.
Even cooler would be if I could dynamically create the predicate just from T with equals between all properties with KeyAttribute and and
in between, so that I wouldn't need the comparer, just T.
时的是的可能吗? :)
推荐答案
假设你可以得到比较器
为表达式来; Func键< T,T,BOOL>>
,那么你可以使用的 LINQKit 来做到这一点。
Assuming you can get comparer
as Expression<Func<T, T, bool>>
, then you can use LINQKit to do this.
是这样的:
Expression<Func<Foo, Foo, bool>> comparer =
(a, b) => a.IdPart1 == b.IdPart1 && a.IdPart2 == b.IdPart2;
Foo instance = …;
Expression<Func<Foo, bool>> predicate = x => comparer.Invoke(x, instance);
var expandedPredicate = predicate.Expand();
var result = FooRepository.GetAll().Where(expandedPredicate);
的
展开()
部分是很重要的,因为这是LINQKit的神奇的发生。稍微不同的语法做同样的事情,就是用 AsExpandable()
而不是:
The Expand()
part is important, because that's where LINQKit's "magic" happens. A slightly different syntax to do the same thing is to use AsExpandable()
instead:
var result = FooRepository.GetAll().AsExpandable().Where(predicate);
这篇关于T,T,BOOL>从Func键<获取; + T实例表达式来; Func键< T,BOOL>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!