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)

5
  • 1
    What kvp.Key is in means? When it's in? When it's out? Commented Oct 22, 2015 at 19:58
  • PropertyInfo.SetValue Commented Oct 22, 2015 at 20:00
  • TL;DR. Are you looking for "C# set property with reflection" - stackoverflow.com/questions/619767/… Commented Oct 22, 2015 at 20:01
  • I can assume that you want to assign values from dictionary to object's properties matching properties names to dictionary keys. But your dictionary contains only string values. How MyClass look like? What types of properties it has? Commented Oct 22, 2015 at 20:01
  • @AlexeiLevenkov yes perfect didnt find this :) Commented Oct 22, 2015 at 20:02

1 Answer 1

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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thansk for this, sorry I realized my mistake with the .Value when eviewing my code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.