-2

happy new year !

I have collected data from an OPC UA server, the data is :

0;0;0;0;0;

I need to write this data to my OPC UA server, the good syntax need to be :

UInt16[] temp = { 0, 0, 0, 0, 0 };

How can I convert the first string to have my array of Uint16 ?

  • Can you post the real string , pls – Serge Jan 05 '22 at 17:24
  • 3
    Break the question down into parts: (1) split the string into parts, (2) parse the split-up strings into UInt16, and (3) put the UInt16 values into an array. – Joe Sewell Jan 05 '22 at 17:26
  • 1
    Does this answer your question? [Split string, convert ToList() in one line](https://stackoverflow.com/questions/911717/split-string-convert-tolistint-in-one-line) – Satpal Jan 05 '22 at 17:30
  • 1
    `var numbers = "0;0;0;0;0;".Split(';').Select(UInt16.Parse).ToArray();` – Satpal Jan 05 '22 at 17:32

3 Answers3

0

Using linq :

var dataString = "0;0;0;0;0;";
var temp = dataString.Split(';')
           .Where(s => !s.Equals(string.Empty))
           .Select(value => Convert.ToUInt16(value))
           .ToArray();

enter image description here

Alexandre
  • 99
  • 5
0

After using the String.Split() method to split the String, you can use the Convert.ToUInt16() method inside the try-catch block to safely convert the String data to UInt16 type. Developed static methods are available below:

public static UInt16[] Convert(String[] values)
{
  UInt16[] numbers = new UInt16[values.Length - 1];

  try
  {
    for(int i = 0 ; i < values.Length - 1 ; ++i)
      numbers[i] = System.Convert.ToUInt16(values[i]);
  }
  catch(FormatException){}

  return numbers;
}

public static void Print(UInt16[] numbers)
{
  for(int index = 0 ; index < numbers.Length ; ++index)
    System.Console.WriteLine("[{0}]: {1}", index, numbers[index]);
}

Here is the application program that calls the static methods:

String[] values= "1;2;3;4;5;".Split( ';' );
uint size = (uint)values.Length - 1;
UInt16[] numbers = new UInt16[size];
numbers = Convert(values);
Print(numbers);

This program produces the following output:

[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
Sercan
  • 4,739
  • 3
  • 17
  • 36
-1

thanks all, Finally it's working with this :

string data = childNode.InnerXml; //0;0;0;0;0;

string[] words = data.Split(';').SkipLast(1).ToArray(); //need to remove the last empty element of the array
                                    
UInt16[] myInts = Array.ConvertAll(words, s => UInt16.Parse(s));
  • 2
    *need to remove the last empty element of the array* - that's what `StringSplitOptions.RemoveEmptyEntries` does – haldo Jan 05 '22 at 17:38