0

I have a Dictionary this contains value pairs that I want to match and update in an instance of a class I have.

So for example I have;

name -> test
userid -> 1

In my Class I then have

MyClass.Name
MyClass.UserId

I would like to set the MyClass.Name = test, etc

Currently I have the method below;

 public static GridFilters ParseGridFilters(Dictionary<string,string> data, MyClass myClass)
        {
            foreach (KeyValuePair<string, string> kvp in data)
            {
                Type t = typeof(MyClass);
                t.GetProperty(kvp.Value, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            }

            return myClass;
        }

How do I then check if the kvp.Key is in (regardless of case which I think i've covered with the BindingFlags) and then set the kvp.Value to the myClass.(kvp.Key)

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Matthew Flynn
  • 3,661
  • 7
  • 40
  • 98

1 Answers1

1

You have to save the reference to the property you are retrieving with reflection, then use SetValue to set its value.

There's also an error in your code. From your explanation it seems like the name of the property is in the Key, not the Value

 public static GridFilters ParseGridFilters(Dictionary<string,string> data, MyClass myClass)
    {
        foreach (KeyValuePair<string, string> kvp in data)
        {
            Type t = typeof(MyClass);
            var prop = t.GetProperty(kvp.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            prop.SetValue(myClass, kvp.Value, null);
        }

        return myClass;
    }
AleFranz
  • 771
  • 1
  • 7
  • 13