二维数组c#
本文关键字:二维数组 | 更新日期: 2023-09-27 18:18:23
我将像这样从用户那里获得输入- "99211,99212,99213_1,99214,99215_3"并将其存储在字符串中
string cpt = "99211,99212,99213_1,99214,99215_3";
cptarray = cpt.Split(',');
我得到的输出是
cptarray[0] = "99211"
cptarray[1] = "99212"
cptarray[2] = "99213_1"
cptarray[3] = "99214"
cptarray[4] = "99215_3"
但是我希望输出是:
cptarray[0][0] = "99211",""
cptarray[1][0] = "99212",""
cptarray[2][0] = "99213","1"
cptarray[3][0] = "99214",""
cptarray[4][0] = "99215","3"
如果我需要得到像上面那样的输出,那么我可以使用2D数组吗,这是正确的方法吗?
根据提供的语法:
cptarray[0][0]
...
cptarray[4][0]
你想要一个锯齿形数组,而不是2D数组;你可以在Linq:
的帮助下构造这个数组 var cptarray = cpt
.Split(',')
.Select(number => number.Split('_'))
.Select(items => items.Length == 1 ? new string[] {items[0], ""} : items)
.ToArray();
测试string test = string.Join(Environment.NewLine, cptarray
.Select((line, index) => string.Format("cptarray[{0}] = {1}",
index,
string.Join(", ", line.Select(item => "'"" + item + "'"")))));
Console.Write(test);
输出 cptarray[0] = "99211", ""
cptarray[1] = "99212", ""
cptarray[2] = "99213", "1"
cptarray[3] = "99214", ""
cptarray[4] = "99215", "3"