2

I know I can index a rectangular array with for and foreach loops but I feel like I'm missing some syntax knowledge on how to return one specific whole row of an array.

For example if my [3,6] array was like this

1 2 3 4 5 6

1 2 3 4 5 6

1 2 3 4 5 6

And I want to just print that middle row to the console, is there an easier way to achieve this than using:

int[,] rectArray = new int[3, 6]
{
     {1, 2, 3, 4, 5, 6 },
     {1, 2, 3, 4, 5, 6 },
     {1, 2, 3, 4, 5, 6 }
};

Console.WriteLine("{0} {1} {2} {3} {4} {5}", 
    rectArray[0, 0], 
    rectArray[0, 1], 
    rectArray[0, 2], 
    rectArray[0, 3], 
    rectArray[0, 4], 
    rectArray[0, 5]);

I was hoping there might be something I could do like:

Console.Writeline(rectArray[0,]);

but that does not work for obvious reasons.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
drjenkin
  • 31
  • 1
  • No there is no such way (`rectArray[0,]`) as you mentioned in the question but you can make use of linq for ease. – Jenish Rabadiya Dec 09 '15 at 03:36
  • No. C# has no syntax to directly do what you're asking. If you want help with a specific implementation of such behavior, please post a good [mcve] showing what you've tried, with a precise description of what that code does and how that's different from what you want – Peter Duniho Dec 09 '15 at 03:36
  • I suppose if you wanted to take input from a user to return an index line would you agree a servicable way to go about it would be say: if (string indexSearch == "k") then... 'code' for (int k = 0; k < rectArray.GetLength(1); k++) { Console.Write(rectArray[1, k] + " "); } 'code' – drjenkin Dec 09 '15 at 03:42
  • You could use linq as they do in this question, but it is not that straight forward. http://stackoverflow.com/questions/28144017/how-to-use-linq-with-a-2-dimensional-array – Olivier De Meulder Dec 09 '15 at 03:49

1 Answers1

0

To print the Middle row:

int middleRow = matrix.GetLength(0)/2;//To get the middle row index
rectArray[middleRow].ToList().ForEach(x => Console.Write(x + " "));
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88