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);
posted @ 2020-12-13 14:29  一纸年华  阅读(4)  评论(0编辑  收藏  举报  来源