2D Array. Set all values to specific value

前端 未结 6 1208
甜味超标
甜味超标 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:13

    Well, this might be cheating because it simply moves the looping code to an extension method, but it does allow you to initialize your 2D array to a single value simply, and in a fashion similar to how you can initialize a 1D array to a single value.

    First, as Jon Skeet mentioned, you could clean up your example of initializing a 1D array like this:

    int [] numbers = Enumerable.Repeat(1,20).ToArray();
    

    With my extension method, you will be able to initialize a 2D array like this:

    public static T[,] To2DArray(this IEnumerable items, int rows, int columns)
    {
        var matrix = new T[rows, columns];
        int row = 0;
        int column = 0;
    
        foreach (T item in items)
        {
            matrix[row, column] = item;
            ++column;
            if (column == columns)
            {
                ++row;
                column = 0;
            }
        }
    
        return matrix;
    }
    

提交回复
热议问题