如何组合c#谓词
本文关键字:谓词 组合 何组合 | 更新日期: 2023-09-27 18:09:08
嗨,我有两个谓词。我想知道是否有可能以某种方式将它们结合在一起?第一:
Predicate<object> viewFilter = f =>
{
ExternalUser u = f as ExternalUser;
return u.AgentName.ToLower().StartsWith(agentName.ToLower());
};
第二:Predicate<object> viewFilter = f =>
{
ExternalUser u = f as ExternalUser;
return u.ExternalLogin.ToLower().StartsWith(login.ToLower());
};
这就是连接谓词的样子。
Predicate<object> viewFilter = f =>
{
ExternalUser u = f as ExternalUser;
return u.ExternalLogin.ToLower().StartsWith(login.ToLower()) && u.AgentName.ToLower().StartsWith(agentName.ToLower());
};
我需要这个WPF数据网格过滤器,其中网格源是ICollectionView。因此,在创建谓词之后,我将其设置为过滤器,如下所示:
private void FilterByLogin(ICollectionView view, string login)
{
Predicate<object> viewFilter = f =>
{
ExternalUser u = f as ExternalUser;
return u.ExternalLogin.ToLower().StartsWith(login.ToLower());
};
view.Filter = viewFilter;
}
我将创建两个新方法:
public static Prediate<object> Cast<T>(Predicate<T> inner)
{
return new Predicate<object>(o => inner((T)o));
}
public static Predicate<T> And<T>(Predicate<T> p1, Predicate<T> p2)
{
return x => p1(x) && p2(x);
}
则可以从谓词中删除强制转换,并将其移动到顶层:
Predicate<ExternalUser> first = u => u.AgentName.ToLower().StartsWith(agentName.ToLower());
Predicate<ExternalUser> second = u => u.ExternalLogin.ToLower().StartsWith(login.ToLower());
view.Filter = Cast(And(first, second));
真的应该像这样简单:
Predicate<object> viewFilter1 = f =>
{
ExternalUser u = f as ExternalUser;
return u.AgentName.ToLower().StartsWith(agentName.ToLower());
};
Predicate<object> viewFilter2 = f =>
{
ExternalUser u = f as ExternalUser;
return u.ExternalLogin.ToLower().StartsWith(login.ToLower());
};
Predicate<object> viewFilter = f => viewFilter1(f) && viewFilter2(f);