| | | 1 | | using System.Collections; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Dynamic; |
| | | 4 | | |
| | | 5 | | namespace WireMock.Extensions |
| | | 6 | | { |
| | | 7 | | /// <summary> |
| | | 8 | | /// Dictionary Extensions |
| | | 9 | | /// </summary> |
| | | 10 | | public static class DictionaryExtensions |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Converts IDictionary to an ExpandObject. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <typeparam name="T"></typeparam> |
| | | 16 | | /// <param name="dictionary">The dictionary.</param> |
| | | 17 | | /// <returns></returns> |
| | | 18 | | public static dynamic ToExpandoObject<T>(this IDictionary<string, T> dictionary) |
| | 0 | 19 | | { |
| | 0 | 20 | | dynamic expando = new ExpandoObject(); |
| | 0 | 21 | | var expandoDic = (IDictionary<string, object>)expando; |
| | | 22 | | |
| | | 23 | | // go through the items in the dictionary and copy over the key value pairs) |
| | 0 | 24 | | foreach (var kvp in dictionary) |
| | 0 | 25 | | { |
| | | 26 | | // if the value can also be turned into an ExpandoObject, then do it! |
| | 0 | 27 | | var value = kvp.Value as IDictionary<string, object>; |
| | 0 | 28 | | if (value != null) |
| | 0 | 29 | | { |
| | 0 | 30 | | var expandoValue = value.ToExpandoObject(); |
| | 0 | 31 | | expandoDic.Add(kvp.Key, expandoValue); |
| | 0 | 32 | | } |
| | 0 | 33 | | else if (kvp.Value is ICollection) |
| | 0 | 34 | | { |
| | | 35 | | // iterate through the collection and convert any strin-object dictionaries |
| | | 36 | | // along the way into expando objects |
| | 0 | 37 | | var itemList = new List<object>(); |
| | 0 | 38 | | foreach (var item in (ICollection)kvp.Value) |
| | 0 | 39 | | { |
| | 0 | 40 | | var objects = item as IDictionary<string, object>; |
| | 0 | 41 | | if (objects != null) |
| | 0 | 42 | | { |
| | 0 | 43 | | var expandoItem = objects.ToExpandoObject(); |
| | 0 | 44 | | itemList.Add(expandoItem); |
| | 0 | 45 | | } |
| | | 46 | | else |
| | 0 | 47 | | { |
| | 0 | 48 | | itemList.Add(item); |
| | 0 | 49 | | } |
| | 0 | 50 | | } |
| | | 51 | | |
| | 0 | 52 | | expandoDic.Add(kvp.Key, itemList); |
| | 0 | 53 | | } |
| | | 54 | | else |
| | 0 | 55 | | { |
| | 0 | 56 | | expandoDic.Add(kvp.Key, kvp.Value); |
| | 0 | 57 | | } |
| | 0 | 58 | | } |
| | | 59 | | |
| | 0 | 60 | | return expando; |
| | 0 | 61 | | } |
| | | 62 | | } |
| | | 63 | | } |