2D Array. Set all values to specific value

前端 未结 6 1204
甜味超标
甜味超标 2021-01-02 13:37

To assign specific value to 1D array I\'m using LINQ like so:

        int[] nums = new int[20];
        nums = (from i in nums select 1).ToArray()         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 14:27

    You can create a simple method that loops over all elements and initializes them:

    public static void Fill2DArray(T[,] arr, T value)
    {
        int numRows = arr.GetLength(0);
        int numCols = arr.GetLength(1);
    
        for (int i = 0; i < numRows; ++i)
        {
            for (int j = 0; j < numCols; ++j)
            {
                arr[i, j] = value;
            }
        }
    }
    

    This uses the same syntax as Array.Fill and will work for an array of any type

提交回复
热议问题