C# 数组相关操作

一。int[] 类型数组

1.求int[]数组中的最大值和最小值

  int[] intArr=new int[]{ 1,2,3,4,5,-24,66};
            int a= intArr.Max();
            int b = intArr.Min();
            Console.WriteLine(a); //最大值为66
            Console.WriteLine(b); //最小值为-24

2.判断int[]数组中是否包含某个值

 int[] intArr=new int[]{ 1,2,3,4,5,-24,66};
  bool a= intArr.Contains(3);
  bool b = intArr.Contains(7);
  Console.WriteLine(a); //true
  Console.WriteLine(b); //false

3.判断2个int数组是否相等(比较数组长度和全部元素都一致返回true)

  int[] array1 = { 1, 2, 3, 4, 5 };
            int[] array2 = { 1, 2, 3, 4, 5 };
            int[] array3 = { 1, 2, 3, 4, 6 };
            int[] array4 = { 1, 2, 3 };
            bool a = array1.SequenceEqual(array2);
            bool b = array1.SequenceEqual(array3);
            bool c = array1.SequenceEqual(array4);
            Console.WriteLine(a); //true
            Console.WriteLine(b); //false
            Console.WriteLine(c); //false

4.判断int[]数组中是否包含某个数组

 int[] array1 = { 1, 2, 3, 8, 9 };
            int[] array2 = { 3, 8};

            bool containsConsecutive = false;

            for (int i = 0; i < array1.Length - 1; i++)
            {
                if (array1[i] == array2[0] && array1[i + 1] == array2[1])
                {
                    containsConsecutive = true;
                    break;
                }
            }
            Console.WriteLine(containsConsecutive); //true

 5.连接两个数组并返回新数组

 int[] array1 = { 1, 2, 3, 4, 5 };
 int[] array2 = { 6, 7, 8, 9, 10 };
 int[] newArray = array1.Concat(array2).ToArray();
 foreach (int num in newArray)
 {
     Console.WriteLine(num);
 }
 // 输出结果:1,2,3,4,5,6,7,8,9,10

6.原数组复制到新数组中去(全部复制)

int[] array1 = { 1, 2, 3, 4, 5 };
int[] array2 =new int[array1.Length];
array1.CopyTo(array2, 0);
 // 输出array2结果:1,2,3,4,5

7.原数组复制到新数组中去(形参2代表从放入的位置是array2中索引下标开始)

 int[] array1 = { 1, 2, 3, 4, 5 };
 int[] array2 =new int[10];
 array1.CopyTo(array2,2);
 // 输出array2结果:0,0,1,2,3,4,5,0,0,0

你可能感兴趣的:(C#,数组,算法)