using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Quadarax.Foundation.Core.Reflection.Extensions; namespace Quadarax.Foundation.Core.Object.Extensions { public static class ObjectExt { public static IDictionary GetAllPropertyValues(this object obj,string indentPrefix = null) { var props = new Dictionary(); if (obj == null) return props; if (string.IsNullOrEmpty(indentPrefix)) indentPrefix = string.Empty; var type = obj.GetType(); var propList = type.GetAllProperties(); foreach (var prop in propList) { var val = prop.GetValue(obj, new object[] { }); if (val is IEnumerable enumerable && !(val is string)) { var cnt = 0; foreach (var item in enumerable) { var itemProps = item.GetAllPropertyValues(prop.Name + $"[{cnt}]."); foreach (var ip in itemProps) props.Add(ip.Key, ip.Value); cnt++; } } else props.Add(indentPrefix + prop.Name, val); } return props; } public static void SetAllPropertyValues(this object obj,IDictionary values,string indentPrefix = null, bool silent = false) { if (obj == null) return; if (values == null || values.Count == 0) return; if (string.IsNullOrEmpty(indentPrefix)) indentPrefix = string.Empty; var type = obj.GetType(); var propList = type.GetAllProperties(); foreach (var val in values) { var propName = val.Key; var prop = propList.FirstOrDefault(x => x.Name == val.Key); if (prop == null) if (!silent) throw new InvalidOperationException( $"Cannot locate property '{val.Key}' in class '{obj.GetType().Name}'."); prop.SetValue(obj,val); } } } }