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