如何组合c#谓词

时间:2016-09-28 10:18:33

标签: c# wpf

嗨我有两个谓词。我想知道是否有可能将它们以某种方式加入到一起? 第一:

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;
}

2 个答案:

答案 0 :(得分:2)

我会创建两个新方法:

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));

答案 1 :(得分:1)

真的应该这么简单:

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);