我正在尝试从文件(HL7 消息段)中解析以竖线分隔的文本行,以使该段成为 HL7 消息对象的属性。
我想我根本不理解 n 维数组的概念...
片段看起来像这样
MSH|^~\&||X530^X530^FID|ERIC^NSCC^RSSI|NSCCH|....
我想这样创建一个数组;
数组中的第一项 = {"0","MSH"}
数组中的下一项 = {"1,", "^~\&"}
数组中的下一项 = {"2,", null}
数组中的下一项 = {"3,", "X530^X530^FID"}
我收到错误信息:
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/