tags:

views:

62

answers:

3

Hi

I need to convert a collection of <string,string> to a single string containing all the values in the collection like KeyValueKeyValue... But How do I do this effectively?

I have done it this way at the moment:

parameters = string.Join("", requestParameters.Select(x => string.Concat(x.Key, x.Value)));

But not sure it is the best way to do it, would a string builder be better? I guess the collection will contain a max of 10 pairs.

A: 

String builder would be fine. Use append to add each a string to the string builder.

Basically the only reason why concat, replace, join, string+string , etc are considered not-the-best because they all tend to destroy the current string & recreate a new one.

So when you have adding strings like upto 10-12 time it really means you will destroy & recreate a string that many times.

loxxy
+2  A: 

With such a small collection, there isn't much of a performance concern, but I would probably just use a StringBuilder to Append all of the values.

Like this:

var sb = new Text.StringBuilder;
foreach (var item in requestParameters)
{
    sb.AppendFormat("{0}{1}", item.Key, item.Value);
}
var parameters = sb.ToString();
davisoa
But this is just duplicating what `string.Join` does internally (the OP appears to be on .NET 4.0, so he's got access to the overload that accepts an `IEnumerable<string>`).
Dan Tao
+3  A: 

string.Join used to not really be the best option since it only accepted string[] or object[] parameters, requiring that any select-style queries needed to be completely evaluated and put into an array first.

.NET 4.0 brought with it an overload that accepts IEnumerable<string> -- which is what you are using -- and even an overload that accepts any IEnumerable<T>. These are definitely your best bet as they are now part of the BCL.

Incidentally, cracking open the source for the first overload in Reflector shows code that follows pretty closely to what davisoa suggested:

public static string Join(string separator, IEnumerable<string> values)
{
    if (values == null)
    {
        throw new ArgumentNullException("values");
    }
    if (separator == null)
    {
        separator = Empty;
    }
    using (IEnumerator<string> enumerator = values.GetEnumerator())
    {
        if (!enumerator.MoveNext())
        {
            return Empty;
        }
        StringBuilder builder = new StringBuilder();
        if (enumerator.Current != null)
        {
            builder.Append(enumerator.Current);
        }
        while (enumerator.MoveNext())
        {
            builder.Append(separator);
            if (enumerator.Current != null)
            {
                builder.Append(enumerator.Current);
            }
        }
        return builder.ToString();
    }
}

So in other words, if you were to change this code to use a StringBuilder, you'd just be rewriting what MS already wrote for you.

Dan Tao