Concatenating Lambda Functions in C#

前端 未结 6 1965
臣服心动
臣服心动 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:16

    Actually, that doesn't work. Try to test it with a case where the first condition FAILS but the second one passes. You'll find that it'll return true. The reason is, because when dealing with multicast delegates that return values, only the last value is returned. For example:

            Func predicate = null;
            predicate += t => t.Length > 10;
            predicate += t => t.Length < 20;
    
            bool b = predicate("12345");
    

    This will return TRUE because the last function call returns true (it's less than 20). In order to really make it work, you need to call:

    predicate.GetInvocationList();
    

    which returns an array of delegates. You then need to make sure they ALL return true, for the final result to be true. Make sense?

提交回复
热议问题