DeepClone.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MECF.Framework.Common.Utilities
  9. {
  10. public static class Utils
  11. {
  12. public static StringBuilder PrintLevel(IEnumerable<string> strList, char seperator = '.', string strDataType = "")
  13. {
  14. StringBuilder builder = new StringBuilder();
  15. builder.AppendLine();
  16. string strdata = string.IsNullOrEmpty(strDataType) ? "Data" : strDataType;
  17. builder.Append($"{strdata}: ");
  18. var dict = strList.Select(o => o.Split(seperator)).GroupBy(o => o[0], v => v.ToArray()).ToDictionary(o => o.Key, v => v.ToList());
  19. _PrintLevel(0, dict, builder);
  20. return builder;
  21. }
  22. static void _PrintLevel(int level, Dictionary<string, List<string[]>> dict, StringBuilder builder)
  23. {
  24. foreach (string key in dict.Keys.OrderBy(o => o))
  25. {
  26. builder.AppendLine();
  27. builder.Append('\t', level + 1);
  28. builder.Append(key);
  29. var subDict = dict[key].Where(o => o.Length > level + 1).GroupBy(o => o[level + 1], v => v.ToArray()).ToDictionary(o => o.Key, v => v.ToList());
  30. _PrintLevel(level + 1, subDict, builder);
  31. }
  32. }
  33. public static T DeepClone<T>(T inputObj) where T : class
  34. {
  35. MemoryStream ms = new MemoryStream();
  36. BinaryFormatter bf = new BinaryFormatter();
  37. bf.Serialize(ms, inputObj);
  38. ms.Seek(0, 0);
  39. object obj = bf.Deserialize(ms);
  40. ms.Close();
  41. return obj as T;
  42. }
  43. }
  44. }