HiveBrain v1.2.0
Get Started
← Back to all entries
principlecsharpMajor

LINQ approach to flatten Dictionary to string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqdictionarystringapproachflatten

Problem

I have a Dictionary 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 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?

Solution

Something like this should work:

public static string ToString(this Dictionary 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);
}

Code Snippets

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);
}

Context

StackExchange Code Review Q#8992, answer score: 24

Revisions (0)

No revisions yet.