c# - 使用循环填充二维数组

标签 c# arrays parsing hl7-v2

我正在尝试从文件(HL7 消息段)中解析以竖线分隔的文本行,以使该段成为 HL7 消息对象的属性。

我想我根本不理解 n 维数组的概念...

片段看起来像这样

MSH|^~\&||X530^X530^FID|ERIC^NSCC^RSSI|NSCCH|....

我想这样创建一个数组;

数组中的第一项 = {"0","MSH"}

数组中的下一项 = {"1,", "^~\&"}

数组中的下一项 = {"2,", null}

数组中的下一项 = {"3,", "X530^X530^FID"}

我收到错误信息:

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

最佳答案

二维数组的每个子数组都有 2 个项目(对吧?),所以你应该有一个 2而不是 1作为长度:

string[,] fieldAndIndex = new string[arrayLength, 2];

因为你想要一个计数器变量 I在循环中,你不应该使用 foreach循环:

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

此外,我认为二维数组不适合这里。存储每个元素的索引(这似乎是你想要做的)是不必要的,因为 fieldAndIndex[x, 0]将始终与 x 相同!

您可能想改用简单的一维数组。还有其他可能有用的数据结构:

  • Dictionary<int, string>
  • (int, string)[]
  • string[][]

关于c# - 使用循环填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57520228/

相关文章:

javascript - javascript中千位分隔符分割数字

c# - 在 C# 项目中添加新的过滤器功能

c# - C#中参数的命名约定

c# - 无法拉伸(stretch)内部 StackPanel

c++ - 结构的多维数组 - 段错误

c - 在结构中添加字符

c++ - 将字符串解析为结构变量

python - 递归错误: maximum recursion depth exceeded while using lark in python

c# - MVC Razor AJAX 调用未命中 Controller

javascript - 查找对象数组是否包含其中一个标签的最快方法