Error Checking Using Func Delegate

So, I recently learned about this new trick using the Func delegate and the Lambda expression to avoid multiple validation if the instructions are in my code.

So the code looks something like

 public static void SetParameters(Dictionary<string,object> param)
        {
            Func<Dictionary<string, object>, bool>[] eval = 
            {
                e => e != null ,
                e => e.Count ==2 ,
                e  => e.ContainsKey("Star"),
                e  => e.ContainsKey("Wars")
            };

            var isValid = eval.All(rule => rule(param));

            Console.WriteLine(isValid.ToString());
        }

but my next step is to do some error checking as well. So, for example, if count! = 2 in my previous example, I would like to write an error assembly for a clearer exception further.

So, I thought, how can I achieve this using similar Func and Lamdba notations?

I came up with a rule validation class

public class RuleChecker
    {
        public Dictionary<string, object> DictParam
        {
            get;
            set;
        }

        public string ErrorMessage
        {
            get;
            set;
        }
    } 

Can someone help, how can I achieve this?

+3
source share
1 answer

You can do it:

        List<string> errors = new List<string>();
        Func<Dictionary<string, object>, bool>[] eval = 
        {
            e => { bool ret = e != null; if (!ret) errors.Add("Null"); return ret; },

        List<string> errors = new List<string>();
        Func<bool, string, List<string>, bool> EvaluateWithError = (test, message, collection) =>
        {
            if (!test) collection.Add(message); return test;
        };

        Func<Dictionary<string, object>, bool>[] eval = 
        {
            e => EvaluateWithError(e != null, "Null", errors),
+2

Source: https://habr.com/ru/post/1769283/


All Articles