Concatenating Lambda Functions in C#

前端 未结 6 1967
臣服心动
臣服心动 2020-12-23 14:46

Using C# 3.5 I wanted to build up a predicate to send to a where clause piece by piece. I have created a very simple Console Application to illustrate the solution that I a

6条回答
  •  执念已碎
    2020-12-23 15:15

    "delegate += method" is operator for multicast delegate to combine method to delegate. In the other hand "delegate -= method" is operator to remove method from delegate. It is useful for Action.

    Action action = Method1;
    action += Method2;
    action += Method3;
    action -= Method2;
    action();
    

    In this case, only Method1 and Method3 will run, Method2 will not run because you remove the method before invoke the delegate.

    If you use multicast delegate with Func, the result will be last method.

    Func func = () => 1;
    func += () => 2;
    func += () => 3;
    int result = func();
    

    In this case, the result will be 3, since method "() => 3" is the last method added to delegate. Anyway all method will be called.

    In your case, method "t => t.Amount < 100" will be effective.

    If you want to combine predicate, I suggest these extension methods.

    public static Func AndAlso(
        this Func predicate1, 
        Func predicate2) 
    {
        return arg => predicate1(arg) && predicate2(arg);
    }
    
    public static Func OrElse(
        this Func predicate1, 
        Func predicate2) 
    {
        return arg => predicate1(arg) || predicate2(arg);
    }
    

    Usage

    public static Func GetPredicate() {
        Func predicate = null;
        predicate = t => t.Response == "00";
        predicate = predicate.AndAlso(t => t.Amount < 100);
        return predicate;
    }
    

    EDIT: correct the name of extension methods as Keith suggest.

提交回复
热议问题