I'm attempting to parse a pipe delimited line of text from a file - HL7 message segment - to make the segment a property of an HL7 message object.
I think I"m fundamentally not understanding the concept of n-dimensional arrays...
The segment looks like this
MSH|^~\&||X530^X530^FID|ERIC^NSCC^RSSI|NSCCH|....
I want to create an array thusly;
First item in the array = {"0","MSH"}
Next item in the array = {"1,", "^~\&"}
Next item in the array = {"2,", null}
Next item in the array = {"3,", "X530^X530^FID"}
I get error message:

private string [,] ParseSegment(string ms)
{
int i = 0;
string[] segmentFields = ms.Split('|');//fields for this segment
int arrayLength = segmentFields.Length;
string[,] fieldAndIndex = new string[arrayLength,1];
foreach (string field in segmentFields)
{
fieldAndIndex [i,i] = {{ i,field} };//I'm not sure what to do here!!!!
}
return fieldAndIndex;
}
Each sub array of your 2D array has 2 items (right?), so you should have a 2 instead of a 1 as the length:
string[,] fieldAndIndex = new string[arrayLength, 2];
Since you want a counter variable I in the loop, you should not use a foreach loop:
for (int i = 0 ; i < arrayLength ; i++) {
// here you want the first item of the subarray to be i, and the second item to be the corresponding segment
fieldAndIndex[i, 0] = i.ToString();
fieldAndIndex[i, 1] = segmentFields[i];
}
Also, I don't think a 2D array is suitable here. Storing the index of each element (which is what you seem to be trying to do) is unnecessary, because fieldAndIndex[x, 0] will always be the same as x!
You might want to use a simple 1D array instead. There are other data structures that might be useful:
Dictionary<int, string>(int, string)[]string[][]To understand the basic array in your case you can consider the array to be a 2D Matrix. Similarly you can consider a 3D array a cube. What you are trying to do is add two item in one place
fieldAndIndex [i,i] = {{ i,field} };
So during the first iteration the notation [i,i] evaluates to [0,0] which means the first element in the first row. The proper way to insert these both can be done as shown by the given answer
fieldAndIndex [i,i] = i.ToString();
fieldAndIndex [i,++i] = field.ToString();
I hope this resolves your issue it is better to go through some research on multi dimensional arrays. This and This are some good links to get started on these arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With