为了账号安全,请及时绑定邮箱和手机立即绑定

C# 编辑列表中的上一个数组

C# 编辑列表中的上一个数组

C#
紫衣仙女 2023-09-09 16:51:41
大家好,我想做一件简单的事情:我定义了一个字符串类型的列表。然后,我向数组“行”添加一些文本。一段时间后,我想编辑以前的“行”数组并更改例如行[1]。例如:{ { "text1", "text2", "text3" },   { "text4", "text5", "text6" },   { "text7", "text8", "text9"} };所以我想更改列表“行”中的“text5”。我当前的代码:List<string[]> rows = new List<string[]>();string[] row = new string[3];row[0] = "text1";row[1] = "text2;row[2] = "text3;rows.Add(row);row[0] = "text4";row[1] = "text5;row[2] = "text6;rows.Add(row);row[0] = "text7";row[1] = "text8;row[2] = "text9;rows.Add(row);那么如何编辑“text5”呢?
查看完整描述

2 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

您的代码无法按预期工作,因为数组是引用类型。和


new string[3];

您创建一个数组对象。和


rows.Add(row);

您将指向该对象的引用添加到列表中。您没有添加数组的副本。因此,调用rows.Add(row);3 次后,这 3 行将全部包含对相同且唯一数组的引用。每行将包含{ "text7", "text8", "text9" }


您必须为每一行创建一个新数组。


List<string[]> rows = new List<string[]>();

string[] row = new string[3];

row[0] = "text1";

row[1] = "text2";

row[2] = "text3";

rows.Add(row);


row = new string[3];

row[0] = "text4";

row[1] = "text5";

row[2] = "text6";

rows.Add(row);


row = new string[3];

row[0] = "text7";

row[1] = "text8";

row[2] = "text9";

rows.Add(row);

或者,使用数组初始值设定项


List<string[]> rows = new List<string[]>();

rows.Add(new string[] { "text1", "text2", "text3" });

rows.Add(new string[] { "text4", "text5", "text6" });

rows.Add(new string[] { "text7", "text8", "text9" });

或者,通过组合集合和数组初始值设定项


List<string[]> rows = new List<string[]> {

    new string[] { "text1", "text2", "text3" },

    new string[] { "text4", "text5", "text6" },

    new string[] { "text7", "text8", "text9" }

};

然后您可以使用从零开始的索引访问“text5”


string oldValue = rows[1][1]; // 1st index selects the row, 2nd the array element.

rows[1][1] = "new text5";

或者


string row = rows[1];

string oldValue = row[1];

row[1] = "new text5";

由于rows列表已包含对此数组的引用row,因此现在

rows[1][1] == row[1]和rows[1][1] == "new text 5"。即,您不需要替换列表中的行。


查看完整回答
反对 回复 2023-09-09
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

例如根据您的代码:


// Use SetValue method

rows[1].SetValue("new value of text5", 1);


// or just by index

rows[1][1] = "new value of text5";


查看完整回答
反对 回复 2023-09-09
  • 2 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信