LINQ approach to flatten Dictionary to string

  • I have a Dictionary<string,string> and want to flatten it out with this pattern:



    {key}={value}|{key}={value}|{key}={value}|


    I tried with a LINQ approach at first but couldn't solve it, so I ended up writing an extension method like this:



    public static string ToString(this Dictionary<string,string> source, string keyValueSeparator, string sequenceSeparator)
    {
    if (source == null)
    throw new ArgumentException("Parameter source can not be null.");

    var str = new StringBuilder();
    foreach (var keyvaluepair in source)
    str.Append(string.Format("{0}{1}{2}{3}", keyvaluepair.Key, keyValueSeparator, keyvaluepair.Value, sequenceSeparator));
    var retval = str.ToString();
    return retval.Substring(0,retval.Length - sequenceSeparator.Length); //remove last seq_separator
    }


    Is it possible to solve this with LINQ?


    I would recommend declaring the concerned parameter in the Exception as follows: `throw new ArgumentException("Parameter can not be null.", "source")`

    @LoSauer good but even better is `throw new ArgumentException("Parameter can not be null.", nameof(source));`

  • Mattias

    Mattias Correct answer

    9 years ago

    Something like this should work:



    public static string ToString(this Dictionary<string,string> source, string keyValueSeparator, string sequenceSeparator)
    {
    if (source == null)
    throw new ArgumentException("Parameter source can not be null.");

    var pairs = source.Select(x => string.Format("{0}{1}{2}", x.Key, keyValueSeparator, x.Value));

    return string.Join(sequenceSeparator, pairs);
    }

    ah, the .Select method returns an IEnumerable. any idea of performance on this one versus the good ol' stringbuilder? thank you, btw.

    String.format uses StringBuilder, but in this case it creates a new instance for each enumeration. Trevor's solution is of course faster, but I dont think you need to worry about performance here unless your dictionary is wickedly large :)

    You do not need a String.Format for simple string concatenation and your code is faster without it. Just do `x.Key + keyValueSeparator + x.Value` which the compiler turns into a String.Concat() which only allocates a single new string.

    @Mattias Just for your reference and not that it really matters but you seem to be missing an end bracket on the var pairs line probably before the ToArray() call...

    @Mattias have you tested your code before posting here? It gives compilation error on .NET 4.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM