c# - 动态调整数组大小

标签 c# arrays

我想动态调整数组的大小。一切都会好的,但在示例中我发现有人使用 Array.Resize() 来调整一维数组的大小,但我希望有可能创建锯齿状数组。我从文件行中读取,其中可能是一些由空格分隔的数字 - 因此我需要动态创建的锯齿状数组。 这是我使用它时的类,但我的数组不调整大小:(

class Program
{
    int[][] nodesMatrix = null;
    private void ReadFromFile(string fileName)
    {

        string line;
        int nodesNr;

        if(File.Exists(fileName) )
        {
            StreamReader fileReader = null;
            try
            {
                fileReader = new StreamReader(fileName);
                int lineNr = 0;
                while ((line = fileReader.ReadLine()) != null)
                {
                   int connectionsNr = 0;
                    if (lineNr==0)
                    {
                        nodesNr = Convert.ToInt32(line);
                        nodesMatrix = new int[nodesNr][];
                        for (int i = 0; i < nodesNr;i++ )
                        {
                            nodesMatrix[i] = new int[1];
                        }
                    }
                    else
                    {

                        string tmpNumber = null;
                        foreach (char sign in line)
                        {

                            if (sign != ' ')
                            {

                                tmpNumber += sign;

                            }
                            if (sign == ' ')
                            {

                                if (tmpNumber != null)
                                {

                                    //nodesMatrix[lineNr] = new int[connectionsNr+1];
                                    nodesMatrix[lineNr][connectionsNr] = Convert.ToInt32(tmpNumber);
                                    connectionsNr++;
                                    Array.Resize<int>(ref nodesMatrix[lineNr], connectionsNr); //here i try to resize array                                      

                                }
                                tmpNumber = null;
                            }
                        }
                    }
                     lineNr++;
                }
            }
            finally
            {
                if (fileReader != null)
                    fileReader.Close();
            }
        }

也许你知道怎么做?

最佳答案

也许我不理解您的用例,但在我看来,如果您知道需要调整大小的数据结构,那么最好使用列表或相关结构,而不是数组。您始终可以通过 linq 添加的 .ToArray() 扩展将列表最后转换回数组。

同样,如果您使用泛型,您可以确保拥有一个强类型的多维列表。您同样可以在内部使用一对列表,并创建自己的类来包装它们。

关于c# - 动态调整数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374300/

相关文章:

c# - 如何防止 SelectedIndexChanged 事件在从列表框中删除项目后在列表框中触发

c# - 在不触及 csproj 文件的情况下更改构建目标

java - 如何打印ArrayList中的元素内容?

c# - .NET 中 AJAX 和 ViewState 的行为不一致

c# - 使用 LinQ 创建表时无法确定...的 SQL 类型

javascript - JavaScript 数据结构(如数组)为什么以及如何不固定长度?

c - C 中的静态变量(在 main 中声明)。混淆

php - 这是什么格式[类似于 json]?

c# - List<T> 运算符 == 在 C# 语言规范版本 4 中

php - 需要循环逻辑帮助 - 无法正确比较