一、C#中新建数组的三种方式:
1、int [] a = {1,2,3,4,5,6,7,8,9};
2、int [] a = new int [10];
for (int i = 0; i<a.Length;i++)
{
a[i] =i*i;
}
for (int i = 0;i<a.Length;i++)//将a的值进行打印出来
{
Console.WriteLine(" a[0] ={1}",i,a[i]);
Console.WriteLine( a[i]);//这种写法也可以
}
3、
int[] a = new int[] { 1, 2, 34, 5, 6, 7, 8 };
foreach (int i in a)
{
Console.WriteLine(i);
}
Console.ReadLine();
二、C#中集合的新建
1、List泛型集合:
List<int> list = new List<int>();
list.Add(1); //添加一个元素进去
list.Add(2);
list.Add(3);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.ReadLine();
2、ArrayList集合
ArrayList list = new ArrayList();
list.Add(1);
例如:
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.ReadLine();
3、hashtable集合:
Hashtable ht = new Hashtable();
ht.Add(1, "我是1");
ht.Add(2, "我是2");
ht.Add(3, "我是3");
ht.Add(4, "我是4");
ht.Add(5, "我是5");
foreach (var item in ht.Keys)
{
Console.WriteLine("键是--{0}--值是---{1}", item, ht[item]);
}
Console.ReadLine();
4、字典集合:
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "张三");
dic.Add(2, "李四");
dic.Add(3, "王五");
foreach (KeyValuePair<int, string> kv in dic) //这种遍历的方式是字典集合特殊的遍历,一般使用比较多
{
Console.WriteLine("{0}---{1}", kv.Key, kv.Value);
}
//foreach (var item in dic.Keys) //遍历的第二种方式,用foreach进行遍历
//{
//Console.WriteLine("{0}---{1}", item, dic[item]);
//}
Console.ReadLine();