C#集合类

.Net的集合类

在.NetFramework中集合类有很多种,比如:Array(数组),ArrayList(数组列表),List(列表),HashTable(哈希表),Dictionary(字典),Stack(堆栈) ,Queue(队列)

ArrayList是数组的复杂版本,ArrayList 类提供在大多数Collection类中不提供但不在Array类提供的一些功能,例如:

1、Array的容量是固定的,而ArrayList的容量是根据需要自动扩展的。如果更改了ArrayList.Capacity属性的值。则自动进行内存重新分配和元素复制。

2、特定类型(不包括Object)的Array的性能比ArrayList好,这是因为ArrayList的元素属于Object类型,所以在存储或检索值类型时通常会发生装箱和拆箱

Array位于 System命名空间,而ArrayList位于 Systm.Collections 命名空间

MSDN上集合类的API接口文档:集合 (C#) | Microsoft Docs

C#集合的命名空间

C#集合的三大命名空间:

image

ArrayList

An ArrayList is a collection from a standard System.Collections namespace. It is a dynamic array. It provides random access to its elements. An ArrayList automatically expands as data is added. Unlike arrays, an ArrayList can hold data of multiple data types. Elements in the ArrayList are accessed via an integer index. Indexes are zero based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time. Inserting or deleting an element in the middle of the dynamic array is more costly. It takes linear time.

一个ArrayList是标准System.Collctions命名空间。它是一个动态数组。它提供了随机访问元素。一个ArrayList自动扩展数据添加。与数组,数组列表可以容纳多个数据类型的数据。数组列表中的元素通过一个整数索引访问。索引是零基础。元素的索引,插入和删除的ArrayList需要持续时间。插入或删除一个元素的动态数组更昂贵。线性时间。

List

A List is a strongly typed list of objects that can be accessed by index. It can be found under System.Collections.Generic namespace.

List是一种强类型列表可以通过索引访问的对象的列表。它可以发现在System.Collections.Generic 命名空间。

 

LinkedList

链表是一个通用的双向链表在c#。LinkedList只允许顺序存取。LinkedList允许常量时间插入或者删除操作,但只有顺序存取的元素。由于引用链表需要额外的存储,它们是不切实际等数据项列表的小角色。不同于动态数组,任意数量的物品可以被添加到链表(当然内存限制)而不需要realocate,这是一项昂贵的操作。

LinkedList示例

using System;
using System.Collections.Generic;
 
public class LinkedListExample 
{
    static void Main()
    {
        LinkedList<int> nums = new LinkedList<int>();
 
        nums.AddLast(23);
        nums.AddLast(34);
        nums.AddLast(33);
        nums.AddLast(11);
        nums.AddLast(6);
        nums.AddFirst(9);
        nums.AddFirst(7);
 
        LinkedListNode<int> node = nums.Find(6);
        nums.AddBefore(node, 5);
 
        foreach(int num in nums)
        {
            Console.WriteLine(num);
        }
    }
}

运行结果

image

Dictionary

字典的检索和添加值是非常快的,但字典需要更多的内存,因为每个值也有钥匙。也被称为一个关联数组,字典是一组独特的键和值的集合,其中每字典需要更多的内存,因为每一个value都有对应的key

using System;
using System.Collections.Generic;
 
public class DictionaryExample 
{
    static void Main()
    {
        Dictionary<string, string> domains = new Dictionary<string, string>();
 
        domains.Add("de", "Germany");
        domains.Add("sk", "Slovakia");
        domains.Add("us", "United States");
        domains.Add("ru", "Russia");
        domains.Add("hu", "Hungary");
        domains.Add("pl", "Poland");
 
        Console.WriteLine(domains["sk"]);
        Console.WriteLine(domains["de"]);
 
        Console.WriteLine("Dictionary has {0} items",
            domains.Count);
 
        Console.WriteLine("Keys of the dictionary:");
 
        List<string> keys = new List<string>(domains.Keys);
 
        foreach(string key in keys)
        {
            Console.WriteLine("{0}", key);
        }        
 
        Console.WriteLine("Values of the dictionary:");
 
        List<string> vals = new List<string>(domains.Values);
 
        foreach(string val in vals)
        {
            Console.WriteLine("{0}", val);
        }
 
        Console.WriteLine("Keys and values of the dictionary:");
 
 
        foreach(KeyValuePair<string, string> kvp in domains)
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }
    }
}

Queues

A queue is a First-In-First-Out (FIFO) data structure. The first element added to the queue will be the first one to be removed. Queues may be used to process messages as they appear or serve customers as they come. The first customer which comes should be served first.

队列是先进先出(FIFO)数据结构。第一个元素添加到队列时会将原来的第一个删除。队列可以用来处理消息时出现或按照客户来的顺序。第一个来的客户应该放在第一位。

示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MyCollection
{
    class QueueExample
    {
        static void Main()
        {
            Queue<string> msgs = new Queue<string>();
 
            //入栈[将对象添加到 Queue 的结尾处]
            msgs.Enqueue("Message 1");
            msgs.Enqueue("Message 2");
            msgs.Enqueue("Message 3");
            msgs.Enqueue("Message 4");
            msgs.Enqueue("Message 5");
 
            //出栈[移除并返回位于 Queue 开始处的对象]
            Console.WriteLine(msgs.Dequeue());
            //返回位于 Queue 开始处的对象但不将其移除
            Console.WriteLine(msgs.Peek());
            Console.WriteLine(msgs.Peek());
 
            Console.WriteLine();
 
            foreach (string msg in msgs)
            {
                Console.WriteLine(msg);
            }
        }
    }
}

运行结果

image

更多知识

关于队列的更多知识请参考:http://www.cnblogs.com/tianzhiliang/archive/2010/09/21/1832664.html

Stacks

表示相同任意类型的实例的可变大小的后进先出 (LIFO) 集合。

示例代码

using System;
using System.Collections.Generic;
 
namespace MyCollection
{
    public class StackExample
    {
        static void Main()
        {
            Stack<int> stc = new Stack<int>();
 
            //调用Push方法压入堆栈
            stc.Push(1);
            stc.Push(4);
            stc.Push(3);
            stc.Push(6);
            stc.Push(4);
 
            //元素出堆
            Console.WriteLine(stc.Pop());
            //获取顶部元素对象,并不移除顶部元
            Console.WriteLine(stc.Peek());
            Console.WriteLine(stc.Peek());
 
            Console.WriteLine();
 
            foreach (int item in stc)
            {
                Console.WriteLine(item);
            }
        }
    }
}

运行结果

image

更多资料

更多请查看MSDN:http://msdn.microsoft.com/zh-cn/library/3278tedw(v=vs.110).aspx

Queue,Stack比较

关于Queue、Stack和其它集合的区别,我觉得主要区别:

Queue和Stack的用在特定的情况下,它们的一个特性是,出栈会把元素删除,并且是按照入栈的顺序出栈的

文献资料

HashTable和Dictionry的比较->参考:http://blog.csdn.net/snlei/article/details/3939206

MSDN:http://msdn.microsoft.com/zh-cn/library/ybcx56wz.aspx

C#知识网站:http://www.w3cschool.cc/csharp/csharp-tutorial.html

推荐一篇好文:http://www.cnblogs.com/jesse2013/p/CollectionsInCSharp.html

posted @ 2014-09-01 17:17  赵青青  阅读(2704)  评论(0编辑  收藏  举报