Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to specify InvariantCulture in string.join()?

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" />

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading