Home > Blockchain >  How to specify InvariantCulture in string.join()?
How to specify InvariantCulture in string.join()?

Time:06-11

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?

CodePudding user response:

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));
  • Related