ObjectExt.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Quadarax.Foundation.Core.Reflection.Extensions;
  4. namespace Quadarax.Foundation.Core.Object.Extensions
  5. {
  6. public static class ObjectExt
  7. {
  8. public static IDictionary<string, object> GetAllPropertyValues(this object? obj,string? indentPrefix = null)
  9. {
  10. var props = new Dictionary<string, object?>();
  11. if (obj == null)
  12. return props;
  13. if (string.IsNullOrEmpty(indentPrefix))
  14. indentPrefix = string.Empty;
  15. var type = obj.GetType();
  16. var propList = type.GetAllProperties();
  17. foreach (var prop in propList)
  18. {
  19. var val = prop.GetValue(obj, new object[] { });
  20. if (val is IEnumerable enumerable)
  21. {
  22. var cnt = 0;
  23. foreach (var item in enumerable)
  24. {
  25. var itemProps = item.GetAllPropertyValues(prop.Name + $"[{cnt}].");
  26. foreach (var ip in itemProps)
  27. props.Add(ip.Key, ip.Value);
  28. cnt++;
  29. }
  30. }
  31. else
  32. props.Add(indentPrefix + prop.Name, val);
  33. }
  34. return props;
  35. }
  36. }
  37. }