C#之鋸齒數組的聲明和遍曆(數組的數組)

來源:互聯網
上載者:User

標籤:foreach   code   元素   子數組和   改進   oid   相等   class   static   

1.何為鋸齒數組?

       數組中每行的元素個數不相同。 

2.聲明鋸齒數組。

       聲明數組的數組,其文法主要在數組的聲明中制定多個方括弧對,如:

       int[][] ArrayName;

       第一個括弧對中設定該數組的行數,第二個括弧對定義各行的元素個數,先設定為空白。因為每行中包含的元素個數不相等。

        還有以下聲明:

        初始化包含其他數組的數組(也稱子數組),然後依次初始化子數組。

                 

   ArrayName = new int[2][];   ArrayName = new int[3];   ArrayName = new int[4];

 

        字面值賦值的改進形式:

                   

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

 

         也可以進行簡化,把數組的初始值和聲明放在同一行上,如下:

                    

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

 

3.鋸齒數組的遍曆可以用for迴圈和foreach的方法。

         for迴圈:用兩個for迴圈對數組進行一一遍曆,詳情看代碼。

         foreach: 也是用嵌套的方法,才能得到實際資料。

         為什麼要嵌套呢?因為數組myIntArray4包含int[]元素,而非int元素,所以必須迴圈子數組和數組本身。

 

 static void Main(string[] args)        {            //聲明一個鋸齒數組  三行            int[][] myIntArray4;            myIntArray4 = new int[3][];            myIntArray4[0] = new int[] { 1, 11, 111 };            myIntArray4[1] = new int[] { 2, 22 };            myIntArray4[2] = new int[] { 3, 33, 333, 3333 };            for (int i = 0; i < myIntArray4.Length; i++)            {                for (int j = 0; j < myIntArray4[i].Length; j++)                {                    Console.WriteLine("{0}", myIntArray4[i][j]);                }            }                                                   /*for迴圈*/            foreach (int[] ab in myIntArray4)            {               foreach (int abc in ab)              {                  Console.WriteLine(abc);              }                                                 /*foreach*/            }            Console.Read();        }

 

C#之鋸齒數組的聲明和遍曆(數組的數組)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.