一.先来说说数组的不足(也可以说集合与数组的区别):

1.数组是固定大小的,不能伸缩。虽然System.Array.Resize这个泛型方法可以重置数组大小,但是该方法是重新创建新设置大小的数组,用的是旧数组的元素初始化。随后以前的数组就废弃!而集合却是可变长的

2.数组要声明元素的类型,集合类的元素类型却是object.

3.数组可读可写不能声明只读数组。集合类可以提供ReadOnly方法以只读方式使用集合。

4.数组要有整数下标才能访问特定的元素,然而很多时候这样的下标并不是很有用。集合也是数据列表却不使用下标访问。很多时候集合有定制的下标类型,对于队列和栈根本就不支持下标访问!

二.下面讲述6种常用集合

1.ArrayList类

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList al = new ArrayList();
            al.Add(100);//单个添加
            foreach (int number in new int[6] { 9, 3, 7, 2, 4, 8 })
            {
                al.Add(number);//集体添加方法一//清清月儿 http://blog.csdn.net/21aspnet/ 
            }
            int[] number2 = new int[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 (int i in al)//不要强制转换
            {
                Console.WriteLine(i);//遍历方法一
            }

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

            }
        }
    }
}

2.Stack类

栈,后进先出。push方法入栈,pop方法出栈。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack sk = new Stack();
            Stack sk2 = new Stack();
            foreach (int i in new int[4] { 1, 2, 3, 4 })
            {
                sk.Push(i);//填充
                sk2.Push(i);
            }
            
            foreach (int i in sk)
            {
                Console.WriteLine(i);//遍历
            }

            sk.Pop();
            Console.WriteLine("Pop");
            foreach (int i in sk)
            {
                Console.WriteLine(i);
            }
            
            sk2.Peek();//弹出最后一项不删除//清清月儿 http://blog.csdn.net/21aspnet/ 
            Console.WriteLine("Peek");
            foreach (int i in sk2)
            {
                Console.WriteLine(i);
            }

            while (sk2.Count != 0)
            {
                int i = (int)sk2.Pop();//清空
                sk2.Pop();//清空
            }
            Console.WriteLine("清空");
            foreach (int i in sk2)
            {
                Console.WriteLine(i);
            }
        }
    }
}

3.Queue类

队列,先进先出。enqueue方法入队列,dequeue方法出队列。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue qu = new Queue();
            Queue qu2 = new Queue();
            foreach (int i in new int[4] { 1, 2, 3, 4 })
            {
                qu.Enqueue(i);//填充
                qu2.Enqueue(i);
            }
            
            foreach (int i in qu)
            {
                Console.WriteLine(i);//遍历
            }

            qu.Dequeue();
            Console.WriteLine("Dequeue");
            foreach (int i in qu)
            {
                Console.WriteLine(i);
            }
            
            qu2.Peek();//弹出最后一项不删除
            Console.WriteLine("Peek");
            foreach (int i in qu2)
            {
                Console.WriteLine(i);
            }

            while (qu2.Count != 0)
            {
                int i = (int)qu2.Dequeue();//清空
                qu2.Dequeue();//清空
            }
            Console.WriteLine("清空");
            foreach (int i in qu2)
            {
                Console.WriteLine(i);
            }
        }
    }
}

4.Hashtable类

哈希表,名-值对。类似于字典(比数组更强大)。哈希表是经过优化的,访问下标的对象先散列过。如果以任意类型键值访问其中元素会快于其他集合。GetHashCode()方法返回一个int型数据,使用这个键的值生成该int型数据。哈希表获取这个值最后返回一个索引,表示带有给定散列的数据项在字典中存储的位置。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {

            // Creates and initializes a new Hashtable.
            Hashtable myHT = new Hashtable();
            myHT.Add("one", "The");
            myHT.Add("two", "quick");
            myHT.Add("three", "brown");
            myHT.Add("four", "fox");

            // Displays the Hashtable.//清清月儿 http://blog.csdn.net/21aspnet/ 
            Console.WriteLine("The Hashtable contains the following:");
            PrintKeysAndValues(myHT);
        }


        public static void PrintKeysAndValues(Hashtable myHT)
        {
            foreach (string s in myHT.Keys)
                Console.WriteLine(s);

            Console.WriteLine(" -KEY- -VALUE-");
            foreach (DictionaryEntry de in myHT)
                Console.WriteLine(" {0}: {1}", de.Key, de.Value);
            Console.WriteLine();
        }
    }
}

5.SortedList类

与哈希表类似,区别在于SortedList中的Key数组排好序的。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {

            SortedList sl = new SortedList();
            sl["c"] = 41;
            sl["a"] = 42;
            sl["d"] = 11;
            sl["b"] = 13;

            foreach (DictionaryEntry element in sl)
            {
                string s = (string)element.Key;
                int i = (int)element.Value;
                Console.WriteLine("{0},{1}",s,i);
            }
        }
    }
}

6.NameValueCollection类

官方给NameValueCollection定义为特殊集合一类,在System.Collections.Specialized下。

System.Collections.Specialized下还有HybridDicionary类,建议少于10个元素用HybridDicionary,当元素增加会自动转为HashTable。

System.Collections.Specialized下还有HybridDicionary类,字符串集合。

System.Collections.Specialized下还有其他类大家可以各取所需!

言归正转主要说NameValueCollection,HashTable 和 NameValueCollection很类似但是他们还是有区别的,HashTable 的KEY是唯一性,而NameValueCollection则不唯一!

using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace ConsoleApplication1
{

    class Program
    {

        static void Main(string[] args)
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht.Add("DdpMDisplaySeq".Trim(), "Display Sequence".Trim());
            ht.Add("DdpMNameChi".Trim(), "Name (Chinese)".Trim());
            ht.Add("DdpMNameEng".Trim(), "Name (English)".Trim());
            ht.Add("Comment".Trim(), "Comment".Trim());
            ht.Add("DdpMMarketCode".Trim(), "Market Code".Trim());
            foreach (object key in ht.Keys)
            {
                Console.WriteLine("{0}/{1}    {2},{3}", key, ht[key], key.GetHashCode(), ht[key].GetHashCode());
            }
            Console.WriteLine(" ");//清清月儿 http://blog.csdn.net/21aspnet/ 
            NameValueCollection myCol = new NameValueCollection();
            myCol.Add("DdpMDisplaySeq".Trim(), "Display Sequence".Trim());
            myCol.Add("DdpMNameChi".Trim(), "Name (Chinese)".Trim());
            myCol.Add("DdpMNameChi".Trim(), "Name (English)".Trim());
            myCol.Add("Comment".Trim(), "Comment".Trim());
            myCol.Add("DdpMMarketCode".Trim(), "Market Code".Trim());
            foreach (string key in myCol.Keys)
            {
                Console.WriteLine("{0}/{1} {2},{3}", key, myCol[key], key.GetHashCode(), myCol[key].GetHashCode());
            }

        }

    }


}


C#的6种常用集合类的更多相关文章

  1. Java集合源码学习(五)几种常用集合类的比较

    这篇笔记对几个常用的集合实现,从效率,线程安全和应用场景进行综合比较. >>ArrayList.LinkedList与Vector的对比 (1)相同和不同都实现了List接口,使用类似.V ...

  2. 十六、C# 常用集合类及构建自定义集合(使用迭代器)

    常用集合类及构建自定义集合 1.更多集合接口:IList<T>.IDictionary<TKey,TValue>.IComparable<T>.ICollectio ...

  3. java 中几种常用数据结构

    Java中有几种常用的数据结构,主要分为Collection和map两个主要接口(接口只提供方法,并不提供实现),而程序中最终使用的数据结构是继承自这些接口的数据结构类. 一.几个常用类的区别 1.A ...

  4. Java必知必会的20种常用类库和API

    转载:https://blog.csdn.net/u011001084/article/details/79216958 个人感觉工具类对日常开发是很重要的,所以推荐一下这篇文章,虽然有的类库过时了 ...

  5. AVA正则表达式4种常用功能

    正则表达式在字符串处理上有着强大的功能,sun在jdk1.4加入了对它的支持 下面简单的说下它的4种常用功能: 查询: String str="abc efg ABC";  Str ...

  6. DotNet中几种常用的加密算法

    在.NET项目中,我们较多的使用到加密这个操作.因为在现代的项目中,对信息安全的要求越来越高,那么多信息的加密就变得至关重要.现在提供几种常用的加密/解密算法. 1.用于文本和Base64编码文本的互 ...

  7. [转]jQuery的each方法的几种常用的用法

    下面提一下jQuery的each方法的几种常用的用法 复制代码 代码如下:  var arr = [ "one", "two", "three&quo ...

  8. 快速理解几种常用的RAID磁盘阵列级别

    我发现周围不少人在学习和理解RAID磁盘阵列的原理时,找了很多专业的资料来看,但是因为动手的机会比较少,因此看完以后还是似懂非懂,真正遇到实际的方案设计的时候,还是拿不定主意. 因此,我结合自己在过去 ...

  9. JAVA 正则表达式4种常用的功能

    下面简单的说下它的4种常用功能:   查询:   以下是代码片段: String str="abc efg ABC";    String regEx="a|f" ...

随机推荐

  1. AI 预测蛋白质结构「GitHub 热点速览 v.21.29」

    作者:HelloGitHub-小鱼干 虽然 AI 领域藏龙卧虎,但是本周预测蛋白质结构的 alphafold 一开源出来就刷爆了朋友圈,虽然项目与我无关,但是看着科技进步能探寻到生命机理,吃瓜群众也有 ...

  2. SQL2008 合并多个结构相同的表的所有数据到新的表

    select * into tikua from (select * from tiku20210303 union all select * from tiku) a

  3. 泛型(8)-Java7的"菱形"语法与泛型构造器

    正如泛型方法允许在方法签名中声明泛型形参一样,Java也允许在构造器签名中声明泛型形参,这样就产生了所谓的泛型构造器. package com.j1803;class Foo{ public < ...

  4. [刘阳Java]_纯CSS代码实现内容过滤效果

    继续我们技术专题课,我们今天给大家带来的是一个比较酷炫的"纯CSS代码实现内容过滤效果",没有加入任何JS的效果.全部都是应用CSS3的新增选择器来实现的.先看效果截图 实现思路 ...

  5. [刘阳Java]_JdbcTemplate用法_第11讲

    JdbcTemplate模板提供操作数据库的方法应用,下面我们来说一下它的用法(注意:建议大家结合Spring API文档学习效果更好,因为下面的代码只是"抱砖引玉") 1. 遵循 ...

  6. React 模块与组件

    React 模块与组件 几个重要概念理解 1). 模块与组件 1. 模块: 理解: 向外提供特定功能的js程序, 一般就是一个js文件 为什么: js代码更多更复杂 作用: 复用js, 简化js的编写 ...

  7. python + mysql 实现查询表数据

    实例如下: import pymysqldef select_form(): # 打开数据库连接 db = pymysql.connect("localhost", "r ...

  8. Delimiter must not be alphanumeric or backslash php报错原因

    昨天写了一个小程序,其中用到了正则表达式去匹配内容.  php源代码如下: preg_match("\b(\w+)\b\s+\1\b",$match):   此报错警告的中文意思是 ...

  9. odoo时间过滤

    Odoo中本日.本月.上月过滤器实现方法   Odoo中本日.本月.上月过滤器实现方法<filter string="今日订单" name="today" ...

  10. 在js中对属性的操作

    一:访问属性 两种方法: ①:对象名.属性名 function  test(sno,age,sex){      this.sno=sno,      this.age=age, this.sex=s ...