Last active
January 1, 2016 19:48
-
-
Save kkurni/8192444 to your computer and use it in GitHub Desktop.
Dynamic Model mapper will convert dictionary<string,string> into proper object, it is very useful for razor engine. for example you can define Model.Parent.Child as a key and you can parse it to your favourite razor engine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public DynamicModel Convert(Dictionary<string, string> dictionary, bool isStrictGet) | |
{ | |
var customDynamicObject = new DynamicModel(isStrictGet: isStrictGet); | |
foreach (var key in dictionary.Keys) | |
{ | |
AddValueToExpandoRecursive(customDynamicObject, key, dictionary[key], isStrictGet); | |
} | |
return customDynamicObject; | |
} | |
private void AddValueToExpandoRecursive(DynamicModel customDynamicObject, string key, string value, bool isStrictGet) | |
{ | |
key = key.Replace(" ", "").Trim(); | |
var queueKeys = new Queue<string>(key.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries)); | |
AddValueToExpandoRecursive(customDynamicObject, queueKeys, value, isStrictGet); | |
} | |
private void AddValueToExpandoRecursive(DynamicModel customDynamicObject, Queue<string> queueKeys, string value, bool isStrictGet) | |
{ | |
string key = queueKeys.Dequeue(); | |
DynamicModel child = null; | |
if (queueKeys.Count == 0) | |
{ | |
if (customDynamicObject.ContainsKey(key)) | |
{ | |
//get the old expando dictionary | |
child = customDynamicObject.GetValue(key) as DynamicModel; | |
child.ObjectName = value; //set object name | |
} | |
else | |
{ | |
//create new one | |
child = new DynamicModel(objectName: value, isStrictGet: isStrictGet); | |
customDynamicObject.Add(key, child); | |
} | |
} | |
else | |
{ | |
if (customDynamicObject.ContainsKey(key)) | |
{ | |
//get the old expando dictionary | |
child = customDynamicObject.GetValue(key) as DynamicModel; | |
} | |
else | |
{ | |
//create new one | |
child = new DynamicModel(isStrictGet: isStrictGet); | |
customDynamicObject.Add(key, child); | |
} | |
//add child value recursively | |
AddValueToExpandoRecursive(child, queueKeys, value, isStrictGet); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment