C# 打印数组的方法


1. for 循环

using System;
using static System.Console;

namespace syqwq
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            for(int i=0; i<array.Length; i++)
            {
                WriteLine(array[i]);
            }
            
            ReadKey();
        }
    }
}

2. foreach 循环

using System;
using static System.Console;

namespace syqwq
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            foreach(int i in array)
            {
                WriteLine(i);
            }
            
            ReadKey();
        }
    }
}

3. LINQ (有点多此一举的方法......)

using System;
using System.Linq;
using static System.Console;

namespace syqwq
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var a = from item in array
                    select item;
            foreach(var i in a)
            {
                WriteLine(i);
            }
            
            ReadKey();
        }
    }
}

4. 数组转化为字符串

using System;
using static System.Console;

namespace syqwq
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            WriteLine(string.Join(" ", array));

            ReadKey();
        }
    }
}

5. Array.ForEach<T>(T[] array, Action<T> action);

定义

//
// 摘要:
//     对指定数组的每个元素执行指定操作。
//
// 参数:
//   array:
//     从零开始的一维 System.Array,要对其元素执行操作。
//
//   action:
//     要对 array 的每个元素执行的 System.Action`1。
//
// 类型参数:
//   T:
//     数组元素的类型。
//
// 异常:
//   T:System.ArgumentNullException:
//     array 为 null。 - 或 - action 为 null。
public static void ForEach<T>(T[] array, Action<T> action);

实现方法:

using System;
using static System.Console;

namespace syqwq
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            Array.ForEach<int>(array, (int i) => WriteLine(i));

            ReadKey();
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM