4

So a normal Dictionary<string, Action> I use like so:

validationsDictionary["ThisValidation"]();

However, strings can be missed typed. So I would like to use the properties of a model as the key:

validationsDictionary[x => x.ThisProperty]();

But, I don't know exactly what the type is going to be, I have tried these:

Dictionary<Func<Model>, Action>
Dictionary<Expressions<Model>, Action>
Dictionary<Expression<Func<Model>>, Action>

I know some people don't rate using functions as keys. So I could do something like this:

void Validate(Expression<Func<Model>> key) 
{
    validationsDictionary[key.ToString()]();
}

I don't know if key.ToString() is a correct property to use, but you get the gist.

EDIT

So, I used this:

Expression<Func<DisplayContentViewModel, object>> predicate

And it works like a treat giving me the ability to do: x => x.SomeProperty

I figured I can use predicate.Name to give a string representation of the name. So now all I have to figure out, is how to populate the dictionary!

Callum Linington
  • 14,213
  • 12
  • 75
  • 154

1 Answers1

1

So after looking at @SriramSakthivel comment about how to get property name from lambda, and I combined it with my code so far I got this as a working solution:

private void Validate(Expression<Func<DisplayContentViewModel, object>> propertyLambda)
{
    var key = this.GetValidationKey(propertyLambda);

    this.validationsDictionary[key]();
}

private void CreateValidationRule(
    Expression<Func<DisplayContentViewModel, object>> propertyLambda,
    Action validationAction)
{
    if (this.validationsDictionary == null)
    {
        this.validationsDictionary = new Dictionary<string, Action>();
    }

    var key = this.GetValidationKey(propertyLambda);

    if (this.validationsDictionary.ContainsKey(key))
    {
        return;
    }

    this.validationsDictionary.Add(key, validationAction);
}

private string GetValidationKey(Expression<Func<DisplayContentViewModel, object>> propertyLambda)
{
    var member = propertyLambda.Body as UnaryExpression;

    if (member == null)
    {
        throw new ArgumentException(
            string.Format("Expression '{0}' can't be cast to a UnaryExpression.", propertyLambda));
    }

    var operand = member.Operand as MemberExpression;

    if (operand == null)
    {
        throw new ArgumentException(
            string.Format("Expression '{0}' can't be cast to an Operand.", propertyLambda));
    }

    return operand.Member.Name;
}
Callum Linington
  • 14,213
  • 12
  • 75
  • 154