1

How I can create and display random integer 2-D array with LINQ? Help me please! I create random 2-D array, but not with LINQ.

Random rnd = new Random();

int[,] matrix = new int[rows, columns];
for (int i = 0; i < matrix.GetLength(0); i++)
    for (int j = 0; j < matrix.GetLength(1); j++)
        matrix[i, j] = rnd.Next(-100,100);
Console.WriteLine("Array:");
for (int i = 0; i < matrix.GetLength(0); i++)
{
    for (int j = 0; j < matrix.GetLength(1); j++)
        Console.Write("{0}\t", matrix[i, j]);
    Console.WriteLine();
}
StaWho
  • 2,488
  • 17
  • 24
  • LINQ will most likely result in less performant and less readable code. It doesn't play well with multi-dimensional arrays in general. – Tim Schmelter Sep 18 '14 at 19:51
  • As nice of a technology as LINQ is, sometimes its not needed and other times, its not only not needed, but it would overly complicate your code, rather than simplify it. This is an example of the latter. – Icemanind Sep 18 '14 at 21:19

2 Answers2

2

Using linq to create a 10x10 array:

   var r = new Random();
   var result = Enumerable.Range(0, 10).Select(x => 
                   Enumerable.Range(0, 10).Select(y => r.Next()).ToArray())
               .ToArray();
brz
  • 5,926
  • 1
  • 18
  • 18
  • I think it returns jagged array but not 2D array – palazzo train Sep 20 '14 at 11:38
  • Many people had searched for a linq way to convert jagged array to 2d array but none was found. Usually they did it by for loop. http://stackoverflow.com/questions/9774901/how-to-convert-list-of-arrays-into-a-2d-array – palazzo train Sep 20 '14 at 11:45
0

If you really want to over-complicate this:

    static void Main(string[] args)
    {
        int rows = 10;
        int columns = 10;
        int[,] matrix = new int[rows, columns];
        Random rnd = new Random();

        Enumerable.Range(0, rows)
            .ToList()
            .ForEach(row => Enumerable.Range(0, columns)
                .ToList()
                .ForEach(column => 
                    {
                        matrix[row, column] = rnd.Next(-100, 100);
                        Console.Write(column == columns ? Environment.NewLine + matrix[row, column].ToString() + "\t" : matrix[row, column].ToString() + "\t");
                    }));

        Console.ReadKey();
    }
StaWho
  • 2,488
  • 17
  • 24