简体   繁体   English

如何将行添加到2D数组

[英]How to add a row to 2D array

I have an array with 89395 rows and 100 columns. 我有一个89395行和100列的数组。

float[][] a = Enumerable.Range(0, 89395).Select(i => new float[100]).ToArray();

I wanna get the index of last row from this array and add one row(lastindex+1) to array and insert 100 floats to the new row which are random. 我想从该数组中获取最后一行的索引,并向该数组添加一行(lastindex + 1),然后将100个浮点数插入随机的新行中。 Also save the new index (number of new row) into the userid variable. 还将新索引(新行数)保存到userid变量中。 I wrote the below code in C#. 我用C#编写了以下代码。

public float random(int newitemid)
{
    a.Length = a.Length+1;
    int userid = a.Length;
    Random randomvalues = new Random();
    float randomnum;
    for (int counter = 0; counter < 100; counter++)
    {
        randomnum = randomvalues.Next(0, 1);
        a[counter] = randomnum;
    }
    return a;
}

You could do this: 您可以这样做:

public float random(int newitemid)
{
    // Create a new array with a bigger length and give it the old arrays values
    float[][] b = new float[a.Length + 1][];
    for (int i = 0; i < a.Length; i++)
        b[i] = a[i];
    a = b;

    // Add random values to the last entry
    int userid = a.Length - 1;
    Random randomvalues = new Random();
    float randomnum;
    a[userid] = new float[100];
    for (int counter = 0; counter < 100; counter++)
    {
        randomnum = (float)randomvalues.NextDouble(); // This creates a random value between 0 and 1
        a[userid][counter] = randomnum;
    }
    return a;
}

However, if you use this method more than once or twice, you really should consider using a list, that's alot more efficient. 但是,如果您多次使用此方法,那么您确实应该考虑使用列表,这样会更有效。

So use List<float[]> a instead. 因此,请使用List<float[]> a代替。

PS If you don't use the parameter newitemid, then it's better to remove it from the function I guess. PS:如果您不使用参数newitemid,那么最好将其从我猜想的函数中删除。

Edit: I updated the randomnum to actually generate random numbers instead of 0's 编辑:我更新了randomnum实际生成随机数,而不是0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM