Best way to convert collection to string

I need to convert a collection <string,string>to a single line containing all the values ​​in the collection, such as KeyValueKeyValue ... But how to do this efficiently?

I have done this at the moment:

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

But not sure if this is the best way to do this, would a line builder be better? I think the collection will contain a maximum of 10 pairs.

+5
source share
3 answers

With such a small collection of performance issues, there are not many, but I would probably just use StringBuilder to add all 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();
+4
source

string.Join , string[] object[], , select - .

.NET 4.0 , IEnumerable<string> - , > - , IEnumerable<T>. , BCL.

, Reflector , davisoa:

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

, , StringBuilder, , MS .

+5

. append .

Basically the only reason concat, replace, join, string + string, etc. are not considered the best, because they all strive to destroy the current line and recreate a new one.

Therefore, when you add lines, such as up to 10-12 times, it really means that you will destroy and recreate the line that is many times.

0
source

All Articles