二维数组的简单用法

    public class IntArrayDemo
    {
        public static void Print()
        {
            for (int i = 0; i<IntArray.Ints.Length; i++) 
            {
                Console.WriteLine(i);
            }
        }

        public static void GetValue() 
        {
            var First = IntArray.GetFirstRow();
            foreach (int i in First)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("----------------------");
            var Second = IntArray.GetSecondRow();
            foreach (int i in Second)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("----------------------");
            var Third=IntArray.GetThirdRow();
            foreach (int i in Third)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("----------------------");
            int[] firstColumn = IntArray.GetFirstColumn();
            foreach (int i in firstColumn)
            {
                Console.WriteLine(i);
            }
        }
    }

    public class IntArray
    {
        //报错MissingMemberException: The lazily-initialized type does not have a public, parameterless constructor.
        //可以看出执行顺序
      /*  private static Lazy<int[]> ints=new Lazy<int[]>();
        public static int[] Ints=ints.Value;
        static IntArray()
        {

            Ints = Enumerable.Range(0,9).ToArray();
        }
*/
        private static Lazy<int[]> ints = new Lazy<int[]>(() => Enumerable.Range(0, 9).ToArray());
        public static int[] Ints => ints.Value;

        //二维数组

        public static int[,] Array2D = new int[3, 4] {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 }
            };
        // 获取第一行数据
        public static int[] GetFirstRow()
        {
            return Enumerable.Range(0, Array2D.GetLength(1))
                .Select(col => Array2D[0, col])
                .ToArray();
        }

        // 获取第二行数据
        public static int[] GetSecondRow()
        {
            return Enumerable.Range(0, Array2D.GetLength(1))
                .Select(col => Array2D[1, col])
                .ToArray();
        }

        // 获取第三行数据
        public static int[] GetThirdRow()
        {
            return Enumerable.Range(0, Array2D.GetLength(1))
                .Select(col => Array2D[2, col])
                .ToArray();
        }

        // 获取第一列数据
        public static int[] GetFirstColumn()
        {
            return Enumerable.Range(0, Array2D.GetLength(0))
                .Select(row => Array2D[row, 0])
                .ToArray();
        }
    }
posted @ 2024-10-17 23:02  孤沉  阅读(4)  评论(0编辑  收藏  举报