Search code examples
c#arraysparsinghl7-v2

Populate 2D arrays using a loop


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:

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;
    }

Solution

  • 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[][]