.netstringculture

String join with culture invariant


I get huge data of object type as input via a collection. I'm trying to form a query by joining these items with comma.

Inside the select query I do some actions like null check, etc.

This works fine in English. However, when run in French/Spanish due to comma as DecimalSeparator I get values with comma's instead of dot.

Without parsing for double, float, decimal types any other option to make it CultureInvariant?

Sample program:

    var dict = new Dictionary<int, object>()
    {
        { 1, "abc" },
        { 2, "def" },
        { 3, 33 },
        { 4, 44 },
        { 5, 5.5 },
        { 6, 6.6 }
    };
    return string.Join(",", dict.Values.Select(x => x == null ? "null" : x));

In English returns: abc,def,33,44,5.5,6.6

Whereas in Spanish: abc,def,33,44,5,5,6,6

How do I get the same result as English irrespective of culture without parsing for each specific type?


Solution

  • The problem is the implicit call to ToString() in the current culture, in string.Join.

    If you select the string representation you want instead, it should be fine. It's slightly unfortunate that there's no overload of object.ToString accepting a culture, but this should work, for any IFormattable implementation:

    return string.Join(",", dict.Values
        .Select(x => x ?? "null")
        .Select(x => x is IFormattable formattable 
           ? formattable.ToString(null, CultureInfo.InvariantCulture) : x));