Reputation: 17
string[,] table;
Will this really create a table for the console application in C# or is there an alternative way of creating a real table other than putting individual characters?
Upvotes: 1
Views: 87
Reputation: 109035
string[,] table;
Declares (as comments have noted) a two-dimensional array. Thus:
table = new string[2,2];
table[0, 0] = "Top left";
table[0, 1] = "Bottom left";
table[1, 0] = "Top right";
table[1, 1] = "Bottom right":
(Using the obvious orientation.)
Compare:
// Three dimensional:
var table3 = new string[2,2,2];
// Array of arrays
string[][] tt = new string[2][];
tt[0] = new string[2];
tt[1] = new string[3]; // Second row is longer!
tt[0][0] = "Top left";
tt[0][1] = "Top right";
tt[1][0] = "Bottom left";
tt[1][1] = "Bottom right";
tt[1][2] = "Bottom extra right";
These are also known as Jagged Arrays.
EDIT Fuller demonstration of the latter case (which are generally more useful), including two ways to enumeration.
Nested loops are easy to understand, but you always need to (implicitly) have those nested loops.
Flattening into a single dimensional structure which allows a lot more power (because there is generally a lot more support for single dimensional structures across BCL and other libraries)
Of course using SelectMany
is a steeper learning curve and is overkill for this simple case:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main(string[] args) {
Console.WriteLine("Array of arrays");
string[][] tt = new string[2][];
tt[0] = new string[2];
tt[1] = new string[3]; // Second row is longer!
tt[0][0] = "Top left";
tt[0][1] = "Top right";
tt[1][0] = "Bottom left";
tt[1][1] = "Bottom right";
tt[1][2] = "Bottom extra right";
NestedLoops(tt);
Flatten(tt);
}
private static void NestedLoops(string[][] tt) {
Console.WriteLine(" Nested:");
for (int outerIdx = 0; outerIdx < tt.Length; ++outerIdx) {
var inner = tt[outerIdx];
for (int innerIdx = 0; innerIdx < inner.Length; ++innerIdx) {
Console.WriteLine(" [{0}, {1}] = " + inner[innerIdx], outerIdx, innerIdx);
}
}
}
private static void Flatten(IEnumerable<string[]> tt) {
Console.WriteLine(" Falattened:");
var values = tt.SelectMany((innerArray, outerIdx)
=> innerArray.Select((string val, int innerIdx)
=> new { OuterIndex = outerIdx, InnerIndex = innerIdx, Value = val }));
foreach (var val in values) {
Console.WriteLine(" [{0}, {1}] = " + val.Value, val.OuterIndex, val.InnerIndex);
}
}
}
Upvotes: 6
Reputation: 66
As said above, that's a two-dimensional string array. You can see it as a table for sure.
There is also a two-dimensional jagged array which is an array with different lengths. And there is also bigger multi-dimensional arrays as well.
But for your "table", if you got values in the array, you can use for-loop
to get the values out from it. In your case, you need a nested for-loop
to get the values added in, for example, a list box.
Upvotes: 0