C#中数组和集合的相关总结

一、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();

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值