C# 数组操作
动态调整数组大小
Resize
实际上是新数组
// 创建数组 double[] arr = { 0.001d, 0.000025d, 0.3135d }; Console.WriteLine($"原数组大小为 {arr.Length},元素为 {string.Join(",", arr)}。"); // 将大小调整为 5 Array.Resize(ref arr, 5); Console.WriteLine($"新数组大小为 {arr.Length},元素为 {string.Join(",", arr)}"); Console.Read();
结果:
原数组大小为 3,元素为 0.001,2.5E-05,0.3135。 新数组大小为 5,元素为 0.001,2.5E-05,0.3135,0,0
反转数组
Reverse
Console.WriteLine("-------- 完全反转 --------"); string[] a = { "ab", "cd", "ef", "gh" }; Console.WriteLine("原数组:{0}", string.Join(',', a)); Array.Reverse(a); Console.WriteLine("反转后的数组:{0}\n", string.Join(',', a)); Console.WriteLine("-------- 部分反转 --------"); int[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; Console.WriteLine("原数组:{0}", string.Join(',', b)); Array.Reverse(b, 3, 4); Console.WriteLine("反转后的数组:{0}", string.Join(',', b)); Console.Read();
结果:
-------- 完全反转 -------- 原数组:ab,cd,ef,gh 反转后的数组:gh,ef,cd,ab -------- 部分反转 -------- 原数组:0,1,2,3,4,5,6,7,8 反转后的数组:0,1,2,6,5,4,3,7,8
查找符合条件的元素
Find 查找单个元素
FindAll 查找多个元素
WorkItem[] items = { new WorkItem { ID = 1, Title = "工序 1", StartTime = new DateTime(2018,7,1,8,36,0), EndTime = new DateTime(2018,7,2,17,30,0) }, new WorkItem { ID = 2, Title = "工序 2", StartTime = new DateTime(2018, 7, 2, 10, 15, 0), EndTime = new DateTime(2018, 7, 5, 18, 0, 0) } };
// 查找单个元素 WorkItem res = Array.Find(items, i => { DateTime condition = new DateTime(2018, 7, 15); if (i.StartTime > condition) return true; return false; }); // 查找多个元素 WorkItem[] resitems = Array.FindAll(items, i => { DateTime condition = new DateTime(2018, 7, 10); if (i.StartTime > condition) return true; return false; });
查找符合条件的元素索引
FindIndex 返回条件的第一个元素索引。
FindLastIndex 返回符合条件的最后一个元素索引。
int index = Array.FindIndex(src, i => { if (i.Contains("a")) return true; return false; }); Console.WriteLine("找到包含字母“a”的首个元素的索引:{0}", index);
确定数组元素存在
Exists
bool res = Array.Exists(stus, x => x.City == "西安");
复制数组中元素
Copy
int[] arr1 = { 1, 2, 3, 4, 5, 6 }; int[] arr2 = new int[3]; // 从arr1复制4、5、6到arr2数组。 // ①源数组; // ②源数组元素开始复制索引; // ③目标数组; // ④写入元素的索引 // ⑤要复制的元素个数 Array.Copy(arr1, 3, arr2, 0, 3);
本文来自博客园,作者:一纸年华,转载请注明原文链接:https://www.cnblogs.com/nullcodeworld/p/18210640
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)