2015-09-27 38 views
1
string[,] table; 

这会真的为C#中的控制台应用程序创建一个表吗?还是有其他方法创建一个真正的表,而不是放个别字符?[,]有什么用?

+1

这是一个字符串的二维数组,您也可以将其视为一个表。 –

+2

这是一个多维数组:https://msdn.microsoft.com/en-US/library/2yd9wwz4(v=vs.80).aspx –

+0

我建议阅读c#教程。你提供的代码将声明一个2维的字符串数组。这是非常基本的C#。 –

回答

6
string[,] table; 

声明(如评论所指出)一个two-dimensional array。因此:(使用明显的方向性)

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": 

比较:

// 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"; 

这些也被称为Jagged Arrays。后一种情况的

EDIT富勒示范(其通常是更有用的),包括两种方式来枚举。

  • 嵌套循环很容易理解,但是您总是需要(隐含地)拥有这些嵌套循环。

  • 压扁成一个单一的三维结构,其允许更大量的功率(因为跨BCL和其它文库单个三维结构通常很多更多的支持),使用SelectMany是更陡的

当然学习曲线和是矫枉过正这个简单的例子:

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); 
     } 
    } 

} 
+0

我如何显示二维数组? –

+0

@milkway嵌套循环(简单)或LINQ中的'SelectMany'变平(概念上更难但非常强大)。 – Richard

+0

@milkway请参阅编辑 – Richard

0

正如上面所说的,这是一个两维字符串数组。你可以把它看成是一张桌子。

还有一个二维锯齿阵列,它是一个不同长度的阵列。而且还有更大的多维数组。

但是对于你的“表”,如果你在数组中有值,你可以使用for-loop来从中获取值。在你的情况下,你需要一个nested for-loop来获取添加的值,例如,一个列表框。