views:

54

answers:

1

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?

+2  A: 

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),
Preet Sangha
Nice. But shouldn't that be (!test) in the second solution?
Grant Crofton
hahahah yes - thank you!
Preet Sangha
Thanks Preet, that works. But i am wondering if there is a much more generic way like EvaluteWithError Delegate rather a class and i can reuse it rather creating the Func<...> everytime in every class ?.
netmatrix01
you could just create a static class with a static method to encapsulate it.
Preet Sangha