public static dynamic ConvertMembersToArrayIfAny(this object @this, char separator = '_', bool allowNestedConversion = true) { if (separator == ChoCharEx.NUL) { throw new ArgumentException("Invalid separator passed."); } if (@this == null) { return(@this); } if (!(@this is ExpandoObject || @this is ChoDynamicObject || @this is IDictionary <string, object>)) { return(@this); } IDictionary <string, object> expandoDic = (IDictionary <string, object>)@this; IDictionary <string, object> root = new ChoDynamicObject(); object value = null; foreach (var kvp in expandoDic) { var pos = kvp.Key.LastIndexOf(separator); value = allowNestedConversion ? ConvertMembersToArrayIfAny(kvp.Value, separator, allowNestedConversion) : kvp.Value; if (pos <= 0) { root.Add(kvp.Key, value); } else { var key = kvp.Key.Substring(0, pos); var indexValue = kvp.Key.Substring(pos + 1); int index = 0; if (!int.TryParse(indexValue, out index)) { root.Add(kvp.Key, value); } else { if (!root.ContainsKey(key)) { root.Add(key, new object[] { }); } var arrValue = root[key] as object[]; if (index + 1 > arrValue.Length) { Array.Resize(ref arrValue, index + 1); root[key] = arrValue; } arrValue[index] = value; } } } return(root as ChoDynamicObject); }
public static dynamic ConvertMembersToArrayIfAny(this object @this, char?startSeparator = null, char?endSeparator = null, bool allowNestedConversion = true) { if (startSeparator == null || startSeparator.Value == ChoCharEx.NUL) { startSeparator = '['; if (endSeparator == null || endSeparator.Value == ChoCharEx.NUL) { endSeparator = ']'; } } if (@this == null) { return(@this); } if (!(@this is ExpandoObject || @this is ChoDynamicObject || @this is IDictionary <string, object>)) { return(@this); } IDictionary <string, object> expandoDic = (IDictionary <string, object>)@this; IDictionary <string, object> root = new ChoDynamicObject(); object value = null; foreach (var kvp in expandoDic) { value = allowNestedConversion ? ConvertMembersToArrayIfAny(kvp.Value, startSeparator, endSeparator, allowNestedConversion) : kvp.Value; var pos = kvp.Key.LastIndexOf(startSeparator.Value); if (pos <= 0) { root.Add(kvp.Key, value); } else { var key = kvp.Key.Substring(0, pos); var indexValue = kvp.Key.Substring(pos + 1); if (endSeparator != null && indexValue.IndexOf(endSeparator.Value) >= 0) { indexValue = indexValue.Substring(0, indexValue.IndexOf(endSeparator.Value)); } int index = 0; if (!int.TryParse(indexValue, out index)) { root.Add(kvp.Key, value); } else { if (!root.ContainsKey(key)) { root.Add(key, new object[] { }); } var arrValue = root[key] as object[]; if (index + 1 > arrValue.Length) { Array.Resize(ref arrValue, index + 1); root[key] = arrValue; } arrValue[index] = value; } } } return(root as ChoDynamicObject); }