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;}
}
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.
Is it possible to set a dictionary value to a class? Yes, it's possible.
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.
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.
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);
}
}
Use
MyClass yourinstance...
foreach (var KVP in myDictionary)
{
yourinstance.GetType().GetProperty ( KVP.Key ).GetSetMethod().Invoke ( yourinstance, new object[] { KVP.Value } );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With