2D Array. Set all values to specific value

前端 未结 6 1170
甜味超标
甜味超标 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条回答
  •  醉梦人生
    2021-01-02 14:15

    If you really want to avoid nested loops you can use just one loop:

    int[,] nums = new int[x,y];
    for (int i=0;i

    You can make it easier by throwing it into some function in a utility class:

    public static T[,] GetNew2DArray(int x, int y, T initialValue)
    {
        T[,] nums = new T[x, y];
        for (int i = 0; i < x * y; i++) nums[i % x, i / x] = initialValue;
        return nums;
    }
    

    And use it like this:

    int[,] nums = GetNew2DArray(5, 20, 1);
    

提交回复
热议问题