Thursday, 30 June 2016

Dictionary Extension Method: Getting an aligned output string


Wouldn't it be nice to convert a dictionary into an aligned string like below?

Well, here is a handy extension method for Dictionary!

public static class DictionaryToString
    {
        public static string ToAlignedString(this Dictionary<string, string> dictionary)
        {
            StringBuilder sb = new StringBuilder();

            var longestStringLength = dictionary.Keys.Max(x => x.Length) + 1;

            foreach (var data in dictionary)
            {
                var spacesToAdd = longestStringLength - data.Key.Length;                
                sb.AppendLine(data.Key + String.Concat(Enumerable.Repeat(" ", spacesToAdd)) + data.Value);
            }

            return sb.ToString();
        }
    }

Basically, for each line in the string, we find the offset between the longest Key ("Arthur") and the other Keys, add " " to the difference to make the Keys the same length and then suffixing the Value. Simple.

We use Enumerable.Repeat for adding spaces to the string in relation to the longest key name.

Finally, we can use the code like this:

    public class Program
    {
        public static void Main(string[] args)
        {
            var data = new Dictionary<string, string>();

            data.Add("Lee", "27");
            data.Add("Sarah", "27");
            data.Add("Arthur", "0.15");
            data.Add("x", "555");
            data.Add("x1", "1");

            Console.WriteLine(data.ToAlignedString());
            Console.ReadKey();
        }
    }

:D

No comments:

Post a Comment