Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to convert collection to string

Tags:

c#

linq

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.

like image 955
Rasmus Christensen Avatar asked Sep 04 '10 19:09

Rasmus Christensen


2 Answers

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.

like image 58
Dan Tao Avatar answered Oct 22 '22 11:10

Dan Tao


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();
like image 38
davisoa Avatar answered Oct 22 '22 13:10

davisoa