【问题标题】:C# Edit previous array in List [duplicate]C#编辑列表中的前一个数组[重复]
【发布时间】:2019-12-24 03:52:24
【问题描述】:

祝大家好运

我想做一个简单的事情:

我定义了一个字符串类型的列表。 然后,我将一些文本添加到数组“行”中。 一段时间后,我想编辑以前的“行”数组并更改例如行[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”呢?

【问题讨论】:

  • rows[1][1] = "..."
  • 我定义了一个字符串类型的列表不,你没有。
  • rows 是一个字符串数组列表。您将“text5”添加到第二个位置的第二个数组(行)。因此,它将是rows[1][1],因为rows[1] 将获得第二行,然后[1] 将获得第二项。我建议你研究一下数组的工作原理并充分理解它们。
  • 你添加相同的数组三次,覆盖以前的值
  • @HansKesting 是的,你是对的。我修好了:)谢谢!

标签: c# arrays list arraylist


【解决方案1】:

您的代码没有按预期工作,因为数组是一种引用类型。与

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"。即,您不需要替换列表中的行。

【讨论】:

  • 感谢这篇非常有用的帖子!我可以使用它的一部分并且它起作用了。非常感谢!
【解决方案2】:

例如基于您的代码:

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

// or just by index
rows[1][1] = "new value of text5";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多