Last active
November 2, 2023 22:45
-
-
Save sean-m/07a973c8c4e04c2f12b7be0b1a48d40d to your computer and use it in GitHub Desktop.
Takes an object and does a naive pass at turing it into a string that would print well in a console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public string ToKvText(object entry) { | |
if (entry == null) return string.Empty; | |
StringBuilder sb = new StringBuilder(); | |
var properties = entry.GetType().GetProperties(); | |
var longestPropertyLength = properties.Select(x => x.Name.Length).Max(); | |
int indentation = longestPropertyLength + 3; | |
foreach (var p in properties) { | |
sb.Append(p.Name.PadRight(longestPropertyLength)); | |
sb.Append(" : "); | |
bool multiLine = false; | |
foreach (var value in (p.GetValue(entry) ?? "NULL").ToString().Split("\n")) { | |
var strValue = value ?? "NULL"; | |
if (multiLine) { | |
sb.AppendLine((strValue).PadLeft(indentation + strValue.Length)); | |
} else { | |
sb.AppendLine((strValue).PadRight(longestPropertyLength)); | |
multiLine = true; | |
} | |
} | |
} | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment