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();
}
}
}
本文作者:咕噜咕噜酱
本文链接:https://www.cnblogs.com/syqwq/p/14393274.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步