0

I'm using AutoMapper for C# and I'm trying to convert a property value into a property name.

Consider the following:

public class ClassA
{
    public string ParamA { get; set; }
    public string ParamB { get; set; }
}

public class ClassB
{
    public string Name { get; set; }
    public string Val { get; set; }
}

I have a list of ClassB instances and I'm trying to convert the value of "Val" property from ClassB into the correct property of ClassA based on the value of "Name":

ClassB b1 = new ClassB() {Name = "ParamA", Val = "ValueA"};
ClassB b2 = new ClassB() {Name = "ParamB", Val = "ValueB"};
ClassB b3 = new ClassB() {Name = "ParamC", Val = "ValueC"};
List<ClassB> listB = new List<ClassB>() {b1, b2, b3};

So using listB I'm trying to create an object of type ClassA with ParamA = "ValueA" and ParamB = "ValueB", is it possible using AutoMapper or any other tool?

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
shod
  • 3
  • 1

2 Answers2

1

is it possible using AutoMapper or any other tool?

You can use Reflection to do something like this:

ClassA a = new ClassA();

foreach (var b in listB)
{
    typeof(ClassA)
        .GetProperty(b.Name) //Get property of ClassA of which name is b.Name
        .SetValue(a , b.Val); //Set the value of such property on object a
}

Please note that based on your question, ClassA should have a property named ParamC.

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
1

I have once found this piece of code on SO and I am using it ever sinc e for these kinds of things. You put this extension method into your class:

    public object this[string propertyName]
    {
      get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
      set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
    }

and then you can use [] to do

ClassA a;
ClassB b;
...
a[b.Name] = b.Val;
Community
  • 1
  • 1
Wapac
  • 4,058
  • 2
  • 20
  • 33
  • I didn't mention that ClassA is 3rd party so I can't add an indexer to it. You're probably correct though, the best way is using Reflection. Thanks! – shod Jan 31 '16 at 14:43