Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;}
}
like image 963
zSynopsis Avatar asked Feb 06 '12 20:02

zSynopsis


People also ask

How do you convert a dictionary to a class?

We are calling a function here Dict2Class which takes our dictionary as an input and converts it to class. We then loop over our dictionary by using setattr() function to add each of the keys as attributes to the class. setattr() is used to assign the object attribute its value.

Can a dictionary value be a class?

Is it possible to set a dictionary value to a class? Yes, it's possible.

How do we fetch values from dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

Can you put a dictionary in a class python?

If you want to use a dictionary globally within a class, then you need to define it in section where you use your class. if you are using your class in main, then define it there. A dictionary or o list are global by default.


2 Answers

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);
     }
}
like image 167
ChrisWue Avatar answered Sep 30 '22 04:09

ChrisWue


Use

MyClass yourinstance...

foreach (var KVP in myDictionary)
{
    yourinstance.GetType().GetProperty ( KVP.Key ).GetSetMethod().Invoke ( yourinstance, new object[] { KVP.Value } );
}
like image 22
Yahia Avatar answered Sep 30 '22 04:09

Yahia