C#中的多维数组

时间:2016-08-02 09:05:22

标签: c#

例如:

int[,] multiArray = new int[2, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };

for (int Row = 0; Row < multiArray.GetLength(0); Row++)
{

    for (int Col = 0; Col < multiArray.GetLength(1); Col++)
    {
         TextBox.Text += multiArray[Row, Col] + "  ";
    }

    TextBox.Text += "\r\n";
}

上面的代码会产生:

1  2  3  4
5  6  7  8

如何将我的2行命名为2014年,2015年并将我的4列命名为1月,4月,7月,10月?

Value [2014, January] or index [0, 0] = 1,
Value [2014, April] or index [0, 1] = 2,
Value [2014, July] or index [0, 2] = 3,
Value [2014, October] or index [0, 3] = 4,
Value [2015, January] or index [1, 0] = 5,
Value [2015, April] or index [1, 1] = 6,
Value [2015, July] or index [1, 2] = 7,
Value [2015, October] or index [1, 3] = 8

当我通过单击打印到TextBox时,按钮会产生类似下面的输出?

      January  April  July  October
2014    1      2      3     4   
2015    5      6      7     8

1 个答案:

答案 0 :(得分:0)

在尝试使用CLI启动WinForms之前。我个人喜欢在CLI中操作字符串,当我确定我知道我在做什么然后才将它翻译成WinForms.Looking你的问题我假设你正在寻找某种日历程序。 /> 知道所有人都会从例子中学到最好的东西,这里是代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] months = { "Jan","Feb","Mar" };
            int[] years = { 2015, 2014, 2013 };
            int[,] important = { { 1, 2, 3 }, { 3, 4, 6 }, { 8, 16, 1 } };

            Console.Write("\t");
            foreach (string month in months)
            {
                Console.Write(month + "\t");
            }
            Console.WriteLine();
            Console.WriteLine();
            foreach (int year in years)
            {
                Console.Write(year.ToString());
                foreach (var month in months)
                {
                    Console.Write("\t" + important[years.ToList<int>().IndexOf(year),months.ToList<string>().IndexOf(month)].ToString());
                }
                Console.WriteLine();
                Console.WriteLine();
            }
            Console.WriteLine();
            Console.ReadKey();

        }
    }
}