Fill a dictionary with properties of a class

Lets come to the most importan class in all this, the “ObjectExtensions” it has 2 functions, one the transfers all the properties of a given class into a IDictionary<string,object> and one that transfers all the Dictionary Key-Value pairs to a given class.

Function “ObjectFromDictionary<t>()”

The function takes a class and a Dictionary and tranfsers all the Key-Value pairs onto the properties of the given class.

But be careful, Boolean, int, float, long, Arrays, Lists, etc. have to be cast as can be seen in the example. My Configuration Class uses a few booleans and their value is saved as string in the dictionary.

If an item can not be transfered a “System.Reflection.TargetException: ‘Object does not match target type.'” is thrown!

 public static T ObjectFromDictionary<T>(IDictionary<string, object> dict) where T:class
{
	_log.Debug("--> ObjectFromDictionary");

	Type myObjectType = typeof(T);
	T result = (T)Activator.CreateInstance(myObjectType);
	foreach (var item in dict)
	{
		if (item.Value.Equals("true") || item.Value.Equals("True"))
				myObjectType.GetProperty(item.Key).SetValue(result, true, null);
		else if(item.Value.Equals("false") || item.Value.Equals("False"))
				myObjectType.GetProperty(item.Key).SetValue(result, false, null);
		else
			myObjectType.GetProperty(item.Key).SetValue(result, item.Value, null);
	}

	_log.Debug("<-- ObjectFromDictionary");

	return result;
}

Function: ObjectToDictionary<T>()

This function takes a class and transfers all the properties into a dictionary in a key-value matter and then returns the dictionary for use.

public static IDictionary<string, object> ObjectToDictionary<T>(T item) where T:class
{
	Type myObjectType = item.GetType();
	IDictionary<string, object> dict = new Dictionary<string, object>();
	PropertyInfo[] properties = myObjectType.GetProperties();
	foreach (PropertyInfo property in properties)
	{
		var value = property.GetValue(item, null);
		dict.Add(property.Name, value);
	}
	return dict;
}

Here you go.

Idea and most of the reflection work was done on stackoverflow 😉

Post on Stackoverflow: https://stackoverflow.com/a/4944155

Thread on Stackoverflow: https://stackoverflow.com/questions/4943817/mapping-object-to-dictionary-and-vice-versa

On the next page is the source-code of both classes 🙂

This entry was posted in C#, PC, programming, Sonstiges, Wissen, Work and tagged , , , , . Bookmark the permalink.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.