C# array類的相關方法

iamzxf發表於2015-05-04


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

namespace arrayDemo2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr1 = new int []{ 1, 2, 3, 4, 5 };
            int[] A = new int[] { 1, 2, 3, 4, 5, 6,7,8 };
            Console.WriteLine(arr1.Length); //返回所有元素的數目
            Console.WriteLine(arr1.Rank);   //一維陣列返回1
            Console.WriteLine(arr1.GetLength(0));
            int[] B1 = (int [])arr1.Clone();
            for (int i = 0; i < B1.Length; i++)
                Console.Write("{0,4}",B1[i]);
            Console.WriteLine();

            B1.CopyTo(A, 2);    //拷貝時,必須保證長度要足夠,否則出問題
            for (int i = 0; i < A.Length; i++)
                Console.Write("{0,4}",A[i]);
            Console.WriteLine();

            Array.Copy(arr1, A, 2);
            for (int i = 0; i < A.Length; i++)
                Console.Write("{0,4}", A[i]);
            Console.WriteLine();

            arr1.Reverse();
            for (int i = 0; i < B1.Length; i++)
                Console.Write("{0,4}", B1[i]);
            Console.WriteLine();

            Array.Sort(arr1);
            for (int i = 0; i < B1.Length; i++)
                Console.Write("{0,4}", B1[i]);
            Console.WriteLine();

            int n = Array.IndexOf(arr1, 7);
            Console.WriteLine(n);

            Console.WriteLine("==============");

            int[,] arr2 = new int[2,3] { {1, 2, 3}, {4, 5,6} };
            Console.WriteLine(arr2.Length); //返回所有元素的數目
            Console.WriteLine(arr2.Rank);   //二維陣列返回2
            Console.WriteLine(arr2.GetLength(0));
            Console.WriteLine(arr2.GetLength(1));
            int[,] B2 = (int[,])arr2.Clone();

            for (int i = 0; i < B2.GetLength(0); i++)
            {
                for (int j = 0; j < B2.GetLength(1); j++)
                    Console.Write("{0,4}", B2[i, j]);
                Console.WriteLine();
            }


            Console.WriteLine("==============");

            int[][] arr3 = new int[3][]{
                new int[2]{1,2},
                new int[4]{1,2,3,4},
                new int[3]{1,2,3}
            };
            Console.WriteLine(arr3.Length); //返回第一維的數目
            Console.WriteLine(arr3.Rank);   //交錯陣列返回1
            Console.WriteLine(arr3.GetLength(0));
            //Console.WriteLine(arr3.GetLength(1));   //對交錯陣列,這行將出錯

            int[][] B3 = (int[][])arr3.Clone();
            for (int i = 0; i < B3.GetLength(0); i++)
            {
                foreach (int j in B3[i])
                    Console.Write("{0,4}",j);
                Console.WriteLine();
            }
                Console.WriteLine("==============");

            Console.ReadLine();
        }
    }
}



相關文章