一、数组
必须规定类型,必须规定长度;
1.定义
int[ ] i = new int[5];
int[] j = new int[]{1,2,3,4,5};
for循环需给初值,步长,末值,foreach则不需要,它是自动遍历集合体中所有值
for循环可用于任何重复行为,foreach循环只能用于遍历
foreach循环遍历速度比for循环快
foreach不能对数据进行修改
2.数组的遍历:
Console.Write(i[0]); //直接输出索引值;
for(int a = 0; a < i.Length; a++)
{ //利用for循环遍历所有数值;
Console.Write(i[a]);
}
foreach(int x in i)
{ //利用foreach输出所有数值;
Console.Write[x];
}
4.二维数组:
int[ , ] erwei = new int [2,3]; //数组长度可以不相同
int[ , ] erwei2 = new int[ , ]{ {1,2,3}, {1,2,3} }; //二位数组长度必须相同
erwei[1, 2] = 1279999; //数组赋值从索引值从0开始,第一个数值定位哪个数组,第二个数值定位当前数组的位置;
二、集合 ArrayList
不需要规定类型、长度;
ArrayList提供添加,删除和插入某一范围元素的方法,但在数组中,只能一次获取或设置一个元素
ArrayList提供将只读和固定大小包装返回到集合的方法,而数组不提供
ArrayList只能是一维形式,而数组可以提供多维的
数组的长度用.legth,集合的长度用.Count
1.定义:
ArrayList arr = new ArrayList(); //需要添加using.System.Collections;类
DateTime dt = new DateTime(1995,06,29); //定义一个时间
2.赋值:
arr.Add("qaz"); //赋值
arr.Add(1234); //赋值
arr.Add(dt); //赋值
Console.Write(arr[0]); //输出索引值
3.遍历:
foreach(var x in arr) //由于不知道数据类型,所以用var类型代替,for循环同理;
{//foreach遍历
Console.WriteLine(arr[]);
}
4.删除:
删除后索引值会重新排;
arr.Remove["qaz"]; //删除指定数值;
arr.RemoveAT[1]; //删除指定索引值的数值;
5.插入:
arr.Insert(2,"孙晓"); //插入索引值前面的位置;
三、泛型集合
不规定长度、规定类型
1.定义:
List<string> ilist = new List<string>();
2.赋值:
ilist.Add("1234"); //赋值
3.插入:
ilist.Insert(1,"孙晓"); //插入
4...
泛型集合使用方法和集合大致相同;
能用泛型就不用集合
集合ArrayList
using System;
using System.Collections;
namespace _01_ArrayList
{
class Program
{
static void Main(string[] args)
{
ArrayList arrayList = new ArrayList();//有三个方式的重载,第二个方式可以传集合,数组
//向集合增加元素,object类型,即任意类型
//看空间增长方式
arrayList.Add(10);
Console.WriteLine("集合的元素个数为:{0}", arrayList.Count);
Console.WriteLine("集合现在的容量:{0}", arrayList.Capacity);
arrayList.Add("10");