Advertisement
Guest User

CollectionPrettyString

a guest
Feb 27th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.83 KB | None | 0 0
  1. public static class CollectionPrettyString
  2. {
  3.     public static string ToPrettyString(this IEnumerable collection)
  4.     {
  5.         if (collection == null) return "null";
  6.  
  7.         var builder = new StringBuilder();
  8.  
  9.         var index = 0;
  10.         builder.Append("[ ");
  11.         foreach (var item in collection)
  12.         {
  13.             if (index > 0) builder.Append(", ");
  14.  
  15.             if (IsValidCollection(item))
  16.                 builder.Append(ToPrettyString(item as IEnumerable));
  17.             else
  18.                 builder.Append(item.ToString());
  19.  
  20.             index++;
  21.         }
  22.         builder.Append(" ]");
  23.  
  24.         return builder.ToString();
  25.     }
  26.  
  27.     public static bool IsValidCollection(object instance)
  28.     {
  29.         if (instance.GetType() == typeof(string)) return false;
  30.  
  31.         return instance is IEnumerable;
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement