DBProcessData.cs 2.5 KB

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