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.0012.5E-050.3135。
    新数组大小为 5,元素为 0.0012.5E-050.313500

反转数组

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

    -------- 部分反转 --------
    原数组:012345678
    反转后的数组:012654378

查找符合条件的元素

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值