集合类

ArrayList

     大小可按需动态增加的数组。

     Capacity是指ArrayList的容量,默认大小是4,当Capacity不够时会申请更多空间,改变之后的Capacity是原来的2倍。

     Count是指当前ArrayList中元素的个数。Count小于或等于Capacity。使用TrimToSizie()可以使Count和Capacity相等。

     ToArray方法返回元素的数组,其中ToArray(Type)可以返回Type类型的数组,返回类型都是System.Array。

ArrayList al = new ArrayList();
Console.WriteLine(al.Capacity);
Console.WriteLine(al.Count);
al.Add(100);            //单个添加
Console.WriteLine(al.Capacity);
Console.WriteLine(al.Count);

foreach (Int32 number in new Int32[6] { 9, 3, 7, 2, 4, 8 })
{
    al.Add(number);    //集体添加方法一
}

Int32[] number2 = new Int32[2] { 11, 12 };
al.AddRange(number2);    //集体添加方法二
al.Remove(3);            //移除值为3的
al.RemoveAt(3);          //移除第3个
ArrayList al2 = new ArrayList(al.GetRange(1, 3));
//新ArrayList只取旧ArrayList一部份

Console.WriteLine("遍历方法一:");
foreach (Int32 i in al)       //不要强制转换
{ 
     Console.WriteLine(i);  //遍历方法一
}

Console.WriteLine("遍历方法二:");
for (Int32 i = 0; i < al2.Count; i++)  //数组是length,ArrayList为Count
{
    Int32 number = (Int32)al2[i];        //一定要强制转换
   Console.WriteLine(number);       //遍历方法二
}

Int32[] intArr = (Int32[])al.ToArray(typeof(Int32));

Queue

Queue:队列,表示对象的先进先出集合。Enqueue方法入队列,Dequeue方法出队列,Peek方法返回队首元素,但是不移除。

Queue qu = new Queue();
Queue qu2 = new Queue();
foreach (Int32 i in new int[4] { 1, 2, 3, 4 })
{
     qu.Enqueue(i);//入队
    qu2.Enqueue(i);
}
foreach (Int32 i in qu)
{
     Console.WriteLine(i); //遍历
}
qu.Dequeue(); //出队
Console.WriteLine("Dequeue");
foreach (Int32 i in qu)
{
     Console.WriteLine(i);
}
qu2.Peek(); //返回位于 Queue 开始处的对象但不将其移除。
Console.WriteLine("Peek");
foreach (Int32 i in qu2)
{
    Console.WriteLine(i);
}

Stack

栈,表示对象的简单的后进先出非泛型集合。Push方法入栈,Pop方法出栈,Peek方法返回栈顶元素,但是不移除。

Stack sk = new Stack();
Stack sk2 = new Stack();
foreach (Int32 i in new int[4] { 1, 2, 3, 4 })
{
     sk.Push(i); //入栈
    sk2.Push(i);
}
foreach (Int32 i in sk)
{
      Console.WriteLine(i); //遍历 从栈顶开始
}
sk.Pop(); //出栈
Console.WriteLine("Pop");
foreach (Int32 i in sk)
{
    Console.WriteLine(i);
}
sk2.Peek();  //弹出最后一项不删除
Console.WriteLine("Peek");
foreach (Int32 i in sk2)
{
    Console.WriteLine(i);
}

 

Hashtable

哈希表,键值对的集合,键值不能重复。

Hashtable ht = new Hashtable();

for (Int32 i = 0; i < 10; i++)
{
    ht.Add(i, (char)('a' + i)); // 同 ht[i] = (char)('a' + i);
}
//添加已经存在的键值时会发生异常
if (ht.Contains(2))     //同ContainsKey  判断是否含有某个键
      Console.WriteLine("The hashtable contains 2");
if (ht.ContainsValue('c'))      //判断是否含有某个值
      Console.WriteLine("The hashtable contains c");

 ht.Remove(5);   //删除键值为5的键值对
 foreach (DictionaryEntry de in ht)    //遍历方法一
 {
      Console.WriteLine(de.Key + "    " + de.Value + "    ");
 }

 ICollection keys = ht.Keys;        
 foreach (Int32 k in keys)          //遍历方法二
 {
      Console.WriteLine(k + "    " + ht[k] + "    ");
  }

SortedList

            SortedList sl = new SortedList();
            sl["c"] = 41;   //同 sl.add(“c”,41);
            sl["a"] = 42;
            sl["d"] = 11;
            sl["b"] = 13;
            foreach (DictionaryEntry element in sl)
            {
                String s = (String)element.Key;
                Int32 i = (Int32)element.Value;
                Console.WriteLine("{0},{1}", s, i);
            }

Dictionary

泛型集合   键值不能重复

            Dictionary<String, String> myDic = new Dictionary<String, String>();
            myDic.Add("aaa", "111");
            myDic.Add("bbb", "222");
            myDic.Add("ccc", "333");
            myDic.Add("ddd", "444");
            //如果添加已经存在的键,add方法会抛出异常
            try
            {
                myDic.Add("ddd","ddd");
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("此键已经存在:" + ex.Message);
            }
            //解决add()异常的方法是用ContainsKey()方法来判断键是否存在
            if (!myDic.ContainsKey("ddd"))
            {
                myDic.Add("ddd", "ddd");
            }
            else
            {
                Console.WriteLine("此键已经存在:");
            
            }
            
            //而使用索引器来赋值时,如果键已经存在,就会修改已有的键的键值,而不会抛出异常
            myDic ["ddd"]="ddd";
            myDic["eee"] = "555";
            
            //使用索引器来取值时,如果键不存在就会引发异常
            try
            {
                Console.WriteLine(myDic["fff"]);
            }
            catch (KeyNotFoundException ex)
            {
                Console.WriteLine("没有找到键引发异常:" + ex.Message);
            }
            //解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
            string value = "";
            if (myDic.TryGetValue("fff", out value))
            {
                Console.WriteLine(value);
            }
            else
            {     
                Console.WriteLine("没有找到对应键的键值"); 
            }
            
            //下面用foreach 来遍历键值对
            //泛型结构体 用来存储健值对
            foreach ( KeyValuePair<String, String> kvp in myDic )
            {
                Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
            }


            //获取键的集合
            foreach(String s in myDic.Keys)
            {
	            Console.WriteLine("key={0}",s);
            }
            //获取值的集合
            foreach (String s in myDic.Values)
            {
                Console.WriteLine("value={0}", s);
            }
            //获取值得另一种方式
            Dictionary<String, String>.ValueCollection values = myDic.Values;
            foreach (String s in values)
            {
                Console.WriteLine("value={0}", s);
            }

泛型集合

     泛型最常见的用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,还有更高的性能,避免了非泛型集合的重复的装箱和拆箱。
    很多非泛型集合类都有对应的泛型集合类,下面是常用的非泛型集合类以及对应的泛型集合类:
非泛型集合类     泛型集合类
ArrayList         List<T>
HashTable       Dictionary<T>
Queue            Queue<T>
Stack             Stack<T>
SortedList      SortedList<T>

 

    

posted on 2010-07-14 15:48  PeterZhang  阅读(1167)  评论(0编辑  收藏  举报