Advertisement
Guest User

Tabbed Console Lines in .Net

a guest
Jan 23rd, 2015
844
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.06 KB | None | 0 0
  1.  
  2.         /// <summary>
  3.         /// Converts a List of string arrays to a string where each element in each line is correctly padded.
  4.         /// Make sure that each array contains the same amount of elements!
  5.         /// - Example without:
  6.         /// Title Name Street
  7.         /// Mr. Roman Sesamstreet
  8.         /// Mrs. Claudia Abbey Road
  9.         /// - Example with:
  10.         /// Title   Name      Street
  11.         /// Mr.     Roman     Sesamstreet
  12.         /// Mrs.    Claudia   Abbey Road
  13.         /// <param name="lines">List lines, where each line is an array of elements for that line.</param>
  14.         /// <param name="padding">Additional padding between each element (default = 1)</param>
  15.         /// </summary>
  16.         /// <remarks>
  17.         /// http://stackoverflow.com/questions/4449021/how-can-i-align-text-in-columns-using-console-writeline
  18.         /// </remarks>
  19.         public string PadElementsInLines(List<string[]> lines, int padding = 1)
  20.         {
  21.             // Calculate maximum numbers for each element accross all lines
  22.             var numElements = lines[0].Length;
  23.             var maxValues = new int[numElements];
  24.             for (int i = 0; i < numElements; i++)
  25.             {
  26.                 maxValues[i] = lines.Max(x => (x.Length > i + 1 && x[i] != null ? x[i].Length : 0)) + padding;
  27.             }
  28.             var sb = new StringBuilder();
  29.             // Build the output
  30.             bool isFirst = true;
  31.             foreach (var line in lines)
  32.             {
  33.                 if (!isFirst)
  34.                 {
  35.                     sb.AppendLine();
  36.                 }
  37.                 isFirst = false;
  38.                 for (int i = 0; i < line.Length; i++)
  39.                 {
  40.                     var value = line[i];
  41.                     // Append the value with padding of the maximum length of any value for this element
  42.                     if (value != null)
  43.                     {
  44.                         sb.Append(value.PadRight(maxValues[i]));
  45.                     }
  46.                 }
  47.             }
  48.             return sb.ToString();
  49.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement