Combine Multiple Predicates

后端 未结 7 718
眼角桃花
眼角桃花 2020-12-01 03:32

Is there any way in c# .NET 2.0! to combine multiple Predicates?

Let\'s say I have the following code.

List names = new List

        
7条回答
  •  一整个雨季
    2020-12-01 04:17

    You could wrap the predicate method into a class and have the constructor accept an array of strings to test for:

    class StartsWithPredicate
    {
        private string[] _startStrings;
        public StartsWithPredicate(params string[] startStrings)
        {
            _startStrings = startStrings;
        }
        public bool StartsWith(string s)
        {
            foreach (var test in _startStrings)
            {
                if (s.StartsWith(test))
                {
                    return true;
                }
            }
            return false;
        }
    }
    

    Then you can make a call like this:

    List filtered = names.FindAll((new StartsWithPredicate("E", "I")).StartsWith);
    

    That way you can test for any combination of input strings without needing to extend the code base with new variations of the StartsWith method.

提交回复
热议问题