How to specify InvariantCulture in string.join()?

525 views Asked by At

I have written the code below in which I am trying to convert an array of type double to a string value using string.join() method. And, then I am adding the string value as an attribute to an XML element.

        XElement element = new("TestNode");
        double[] myDoubleArray = new double[2] { 0.001, 1.0 };
        var stringValue = string.Join(" ", myDoubleArray);
        element.Add(new XAttribute("Values", stringValue));

The output of the above code is

<TestNode Values="0,001 1" />

As can be seen, the value of 0.001 has been written as 0,001 because my system language is German.

QUESTION: How do I create a whitespace separated string from an array of double type (in minimum lines of code) while maintaining InvariantCulture?

1

There are 1 answers

0
Heinzi On BEST ANSWER

Unfortunately, there is no string.Join overload that takes a CultureInfo parameter. Thus, you'll have to do the conversion yourself:

XElement element = new("TestNode");
double[] myDoubleArray = new double[2] { 0.001, 1.0 };

var myDoublesFormatted = myDoubleArray.Select(d => d.ToString(CultureInfo.InvariantCulture));

var stringValue = string.Join(" ", myDoublesFormatted);
element.Add(new XAttribute("Values", stringValue));