DBProcessData.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. namespace DataService;
  2. public class DBProcessData<T_Output, T_PrimaryKey, T_DicValue>(Func<object, T_PrimaryKey?> KeyConverter, char spilter, string keyName)
  3. where T_PrimaryKey : unmanaged
  4. where T_Output : IDictionary<string, object>, new()
  5. where T_DicValue : IDictionary<T_PrimaryKey, object>, new()
  6. {
  7. public bool ToDictionary(IEnumerable<dynamic> inputs, out T_Output? output)
  8. {
  9. output = default;
  10. if (inputs is null)
  11. return false;
  12. T_Output cache = [];
  13. foreach (dynamic input in inputs)
  14. {
  15. if (input is null)
  16. return false;
  17. if ((input as IDictionary<string, object>)?.TryGetValue(keyName, out object? primaryKeyValue) != true || primaryKeyValue is null)
  18. return false;
  19. if (KeyConverter?.Invoke(primaryKeyValue) is not T_PrimaryKey primaryKey)
  20. return false;
  21. (input as IDictionary<string, object>)?.Remove(keyName);
  22. foreach (KeyValuePair<string, object> rawData in input)
  23. ColumAnalizer(cache, rawData.Key.Split(spilter), primaryKey, rawData.Value);
  24. }
  25. output = cache;
  26. return true;
  27. }
  28. private static bool ColumAnalizer(/*ref*/ T_Output cache, Span<string> seprated, T_PrimaryKey key, object value)
  29. {
  30. cache = TryGetValueElseCreateNew<T_Output>(cache, seprated[0]);
  31. _ = seprated.Length switch
  32. {
  33. 1 => TryGetValueElseCreateNew<T_DicValue>(cache, seprated[0]).TryAdd(key, value),//Recursion End
  34. _ => ColumAnalizer(cache, seprated[1..], key, value),//Recursion
  35. };
  36. return true;
  37. }
  38. private static T TryGetValueElseCreateNew<T>(T_Output cache, string key) where T : new()
  39. {
  40. if (!cache.TryGetValue(key, out object? output) || output is not T dic)
  41. {
  42. dic = new();
  43. cache[key] = dic;
  44. }
  45. return dic;
  46. }
  47. }
  48. class GeneralHeaderAnalizer
  49. {
  50. public static DateTime? LongToDateTime(object o)
  51. {
  52. if (o is not long l)
  53. return null;
  54. return new(l);
  55. }
  56. }
  57. public class GeneralProcessData : DBProcessData<Dictionary<string, object>, DateTime, Dictionary<DateTime, object>>
  58. {
  59. public GeneralProcessData() : base(GeneralHeaderAnalizer.LongToDateTime, '.', "time")
  60. {
  61. }
  62. }