zSynopsis
zSynopsis

Reputation: 4854

Populate a class from a Dictionary

I have a dictionary collection of more than 100 fields and values. Is there a way to populate a gigantic class with a 100 fields using this collection?

The key in this dictionary corresponds to the property name of my class and the value would be the Value of the Property for the class.

Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("MyProperty1", "Hello World");
myDictionary.Add("MyProperty2", DateTime.Now);
myDictionary.Add("MyProperty3", true);

Populates the properties of the following class.

public class MyClass
{
   public string MyProperty1 {get;set;}
   public DateTime MyProperty2 {get;set;}
   public bool MyProperty3 {get;set;}
}

Upvotes: 5

Views: 2841

Answers (2)

Yahia
Yahia

Reputation: 70369

Use

MyClass yourinstance...

foreach (var KVP in myDictionary)
{
    yourinstance.GetType().GetProperty ( KVP.Key ).GetSetMethod().Invoke ( yourinstance, new object[] { KVP.Value } );
}

Upvotes: 1

ChrisWue
ChrisWue

Reputation: 19020

You can use GetProperties to get a list of properties for a given type and use SetValue to set a specific value for a given property:

MyClass myObj = new MyClass();
...
foreach (var pi in typeof(MyClass).GetProperties())
{
     object value;
     if (myDictionary.TryGetValue(pi.Name, out value)
     {
          pi.SetValue(myObj, value);
     }
}

Upvotes: 9

Related Questions