C#之数组篇

大杂烩

一、数组初始化

1.一维数组

String[] str = new String[3] { "1","2","3"};

String[] str2 = { "1","2","3"};

2.二维数组

String[,] str = { { "1","2"}, {"3","4" }, {"5","6" } };

String[,] str2 = new String[3, 2] { { "1", "2" }, { "3", "4" }, { "5", "6" } };

二、数组排序

int[] str = {1,20,3,56,85,66,99,9556,464,48,1,115,1553 };

Array.Sort(str);//升序

Array.Reverse(str);//降序

三、数组合并

Array.Copy(str,str2,10);//从索引值0开始,取10个长度放入

Array.Copy(str1,0,str2,10,10);//str1从0开始,str2从10开始,str1向str2复制10个元素

四、ArrayList

引入命名空间:using System.Collections;

添加元素

string[] str = { "张三","李四","王五","赵六"};

ArrayList arrayList = new ArrayList();

// arrayList.AddRange(str);//把元素逐一添加进去

arrayList.Add(str);//当对象添加进去

移除元素

arrayList.Remove("李四");

arrayList.RemoveAt(1);

arrayList.RemoveRange(0, 2);

arrayList.Clear();

查找元素

arrayList.IndexOf("王五");

//BinarySearch查找之前要排序

/*二分查找要求字典在顺序表中按关键码排序,即待查表为有序表。*/

arrayList.Sort();

arrayList.BinarySearch()

五、List

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
非泛型集合
    ArrayList
    Hashtable
泛型集合
    List<T>
    Dictionary<Tkey,Tvalue>

*/
namespace 装箱和拆箱 {
    class Program {
        static void Main(string[] args) {
            List<int> list = new List<int>();
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 });
            foreach(var item in list) {
                Console.WriteLine(item);
            }
            list.RemoveAll(n=>n>2);//筛选移除
            foreach(var item in list) {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}