Question

I have this question from Most efficient Dictionary.ToString() with formatting?, but my problem is if V is List, how to make it works. Now my solution is, change

itemString.AppendFormat(format, item.Key, item.Value);

to

itemString.AppendFormat(format, item.Key, item.Value.ToDelimitedStr());

here is code of ToDelimitedStr:

    public static string ToDelimitedStr<T>(this T source)
    {
        // List<string> 
        if (source is IList &&
            source.GetType().IsGenericType)
        {
            Type t1 = source.GetType().GetGenericArguments()[0];
            if (t1.Name == "String")
                ((IEnumerable<string>)source).ToDelimitedString();
        }
        return source.ToString();
    }

which only work for List<string>. How I can make it more generic? Also, I'm thinking, maybe I should not work on the top of

public string DictToString<T, V>(IEnumerable<KeyValuePair<T, V>> items, string format)

I should create a new version like

public string DictListToString<T, List<V>>(IEnumerable<KeyValuePair<T, List<V>>> items, string format)

how about that?

Thank you so much

Wes

Was it helpful?

Solution

Use string.Join

return string.Join("," , (IList<T>)source); 

I think it would be easier if you add an overloead for ToDelimitedStr which takes a IEnumerable<T> as parameter, then you don't need that type checks:

public static string ToDelimitedStr<T>(this IEnumerable<T> source)
{
     return string.Join(",", source);
}

OTHER TIPS

use IEnumerable and just call ToString on the items:

public static string ToDelimitedStr<T>(this T source)
{
    // Will work for ANY IEnumerable
    if (source is IEnumerable)     // <----------------
    {
        IEnumerable<string> items =
           ((IEnumerable)source).OfType<object>()
                                .Select(o => o.ToString());
        // convert items to a single string here...
        return string.Join(", ", items);
    }
    return source.ToString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top