C# 如何在二维数组中动态添加值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10775565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:12:26  来源:igfitidea点击:

How to dynamically add values in a 2D array?

c#winforms

提问by Momo Pomo

I am working with 2D arrays. what I want, is to dynamically add elements in specific columns of my 2D array named symboltable2. I have been doing it as;

我正在使用二维数组。我想要的是在我的二维数组的特定列中动态添加元素symboltable2。我一直在这样做;

result is another 1D array in which there are certain words:

结果是另一个一维数组,其中有某些单词:

string[,] symboltable2 = new string[,];

if (result.Contains("int")) {
    for (int todynamic = 0; todynamic < result.GetLength(0); todynamic++) {
        symboltable2[todynamic, 6] = "int";
    }
    for (int sym2 = 0; i < symboltable1.GetLength(0); sym2++) {
        f4.listBox6.Items.Add(symboltable1[sym2, 5]); // To show if the values are added or not
    }
} 

but the code above isn't giving me any results... kindly help :(

但上面的代码没有给我任何结果......请帮助:(

回答by sihirbazzz

while implementing arrays you need to give the array's dimension i.e.

在实现数组时,您需要给出数组的维度,即

string[,] sa = new string[5,15];

or

或者

string[,] sa = new string[listString1.Count, listString2.Count] 

about adding / changing elements to 2D array.. as a simple string array example :

关于向二维数组添加/更改元素.. 作为一个简单的字符串数组示例:

sa[0, 1] = "a";
sa[0, 2] = "b";
sa[1, 0] = "Istanbul / Turkey";

回答by Paul Sasik

You need to set the size of the array. And to have it public I would use a property and initialize your array in the class constructor like this:

您需要设置数组的大小。并公开它,我将使用一个属性并在类构造函数中初始化您的数组,如下所示:

public class MyClass
{
    public string[,] symboltable2 { get; set; } 

    public MyClass()
    {
        symboltable2 = new string[10,10];
    }

            // ...