Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Checking using Func Delegate

So i recently learned this new trick of using Func Delegate and Lambda expression to avoid multiple validation if statements in my code.

So the code looks like 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 i would like to do some error checking as well. So for e.g. if the count !=2 in my previous example i would like to write build some error collection for more clear exception further down.

So i been Wondering how can i achieve that using similar Func and Lamdba notation ?.

I did come up with my rules checker class

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

        public string ErrorMessage
        {
            get;
            set;
        }
    } 

Can someone help as how can i achieve this?

like image 843
netmatrix01 Avatar asked Jul 21 '26 07:07

netmatrix01


1 Answers

you can do this:

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

However a more elegant solution would be to

        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),
like image 151
Preet Sangha Avatar answered Jul 23 '26 19:07

Preet Sangha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!