1.栈(stack<T>)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Stack
{
class Program
{
static void Main(string[] args)
{
var stack = new Stack<char>();
stack.Push('A');
stack.Push('B');
stack.Push('C');
stack.Push('D'); foreach (char c in stack)
{
Console.WriteLine(c);
}
Console.WriteLine("普通遍历栈中元素个数为:{0}",stack.Count); Console.WriteLine("Second iteration:");
while (stack.Count > )
{
Console.WriteLine(stack.Pop());
}
Console.WriteLine("Pop()出栈后栈中元素个数为:{0}", stack.Count);
}
}
}

2.队列(Queue<T>)

文档类(Document)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Queue
{
public class Document
{
public string Title
{
get;
private set;
} public string Content
{
get;
private set;
} public Document(string title, string content)
{
this.Title = title;
this.Content = content;
}
} }

文档管理类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Queue
{
/// <summary>
/// 处理文档的类
/// </summary>
public class DocumentManager
{
private readonly Queue<Document> documentQueue = new Queue<Document>();
/// <summary>
/// 将文档添加到队列中
/// </summary>
/// <param name="doc"></param>
public void AddDocument(Document doc)
{
lock (this)//多个线程可以同时访问DocumentManager类,用lock语句锁定对队列的访问
{
documentQueue.Enqueue(doc); //添加到队列结尾
}
} /// <summary>
/// 从队列中获取文档
/// </summary>
/// <param name="doc"></param>
public Document GetDocument()
{
Document doc = null;
lock (this) //多个线程可以同时访问DocumentManager类,用lock语句锁定对队列的访问
{
doc=documentQueue.Dequeue(); //获取并移除队列开始的元素
}
return doc;
} /// <summary>
/// 是否还存在元素
/// </summary>
public bool IsDocumentAvailable
{
get
{
return documentQueue.Count > ;
}
}
}
}

进程管理类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading; namespace Queue
{
public class ProcessDocuments
{
private DocumentManager documentManager;
/// <summary>
/// 实例化一个新任务
/// </summary>
/// <param name="dm"></param>
public static void Start(DocumentManager dm)
{
Task.Factory.StartNew(new ProcessDocuments(dm).Run);
} protected ProcessDocuments(DocumentManager dm)
{
if (dm == null)
{
throw new ArgumentNullException("dm");
}
this.documentManager = dm;
} protected void Run()
{
while (true)
{
if (documentManager.IsDocumentAvailable)
{
Document doc = documentManager.GetDocument();
Console.WriteLine("Processing document{0}",doc.Title);
}
Thread.Sleep(new Random().Next()); //线程挂起事件小于20秒的随机数
} }
}
}

测试类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; namespace Queue
{
class Program
{
static void Main(string[] args)
{
var dm = new DocumentManager();
ProcessDocuments.Start(dm);
for (int i = ; i < ; i++)
{
var doc = new Document("Doc "+ i.ToString(),"content");
dm.AddDocument(doc);
Console.WriteLine("Added document {0}",doc.Title);
Thread.Sleep(new Random().Next());
} }
}
}

显示结果

3.链表(LinkList<T>)

文档类(Document)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace LinkList
{
/// <summary>
/// 操作文档类
/// </summary>
public class Document
{
public string Title { get; private set; }
public string Content { get; private set; }
/// <summary>
/// 优先级
/// </summary>
public byte Priority { get; private set; } public Document(string title, string content, byte priority)
{
this.Title = title;
this.Content = content;
this.Priority = priority;
}
}
}

文档管理(PriorityDocumentManager)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace LinkList
{
public class PriorityDocumentManager
{
//包含所有文档
private readonly LinkedList<Document> documentList;
//最多包含10个元素的索引,添加到指定优先级的新文档的入口点
private readonly List<LinkedListNode<Document>> priorityNodes;
public PriorityDocumentManager()
{
documentList = new LinkedList<Document>();
priorityNodes = new List<LinkedListNode<Document>>();
for (int i = ; i < ; i++)
{
priorityNodes.Add(new LinkedListNode<Document>(null));
}
} /// <summary>
/// 添加文档
/// </summary>
/// <param name="doc">文档</param>
/// <param name="priority">优先级</param>
private void AddDocumentToPriority(Document doc, int priority)
{
if (priority > || priority<)
{
throw new ArgumentException("优先级在1-9之间");
} if (priorityNodes[priority].Value == null)
{
--priority;
if (priority >= )
{
//判断下一个节点的优先级
AddDocumentToPriority(doc, priority);
}
else
{
//优先级节点的优先级值与所传送的优先级不同,也没有比该优先级值更低的优先级节点时
//添加新节点到文件尾
documentList.AddLast(doc);
priorityNodes[doc.Priority] = documentList.Last;
}
return;
}
else //节点的优先级存在
{
LinkedListNode<Document> priorityNode = priorityNodes[priority];
//存在指定优先值的优先级节点
if (priority == doc.Priority)
{ documentList.AddAfter(priorityNode, doc);
priorityNodes[doc.Priority] = priorityNode.Next;
}
else
{
//存在以较低的优先值引用文档的优先级节点
//获取一个较低优先值的节点
LinkedListNode<Document> firstPriority = priorityNode;
while (firstPriority.Previous != null && firstPriority.Previous.Value.ToString() == priorityNode.Value.ToString())
{
firstPriority = priorityNode.Previous;
priorityNode = firstPriority;
}
documentList.AddBefore(firstPriority, doc);
//给节点设置新的优先值
priorityNodes[doc.Priority] = firstPriority.Previous;
}
} } /// <summary>
/// 添加文档和优先值
/// </summary>
/// <param name="doc"></param>
public void AddDocument(Document doc)
{
if (doc == null)
{
throw new ArgumentNullException("doc");
}
AddDocumentToPriority(doc, doc.Priority);
} /// <summary>
/// 显示文档节点
/// </summary>
public void DisplayAllNodes()
{
foreach (Document doc in documentList)
{
Console.WriteLine("priority:{0},title:{1}",doc.Priority,doc.Title);
}
} /// <summary>
/// 返回最大优先值的节点
/// </summary>
/// <returns></returns>
public Document GetDocument()
{
Document doc = documentList.First.Value;
documentList.RemoveFirst();
return doc;
}
}
}

测试类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace LinkList
{
class Program
{
static void Main(string[] args)
{
var priorityDoc = new PriorityDocumentManager();
priorityDoc.AddDocument(new Document("one","Sample",));
priorityDoc.AddDocument(new Document("two", "Sample", ));
priorityDoc.AddDocument(new Document("three", "Sample", ));
priorityDoc.AddDocument(new Document("four", "Sample", ));
priorityDoc.AddDocument(new Document("five", "Sample", ));
priorityDoc.AddDocument(new Document("six", "Sample", ));
priorityDoc.AddDocument(new Document("seven", "Sample", ));
priorityDoc.AddDocument(new Document("eight", "Sample", )); priorityDoc.DisplayAllNodes();
}
}
}

显示结果:

4.字典(Dictionary<TKey, TValue>)

键(EmployeeId)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts; namespace Dictionary
{
[Serializable]
public class EmployeeIdException : Exception
{
public EmployeeIdException(string message) : base(message) { }
} [Serializable]
public struct EmployeeId : IEquatable<EmployeeId>
{
private readonly char prefix;
private readonly int number;
public EmployeeId(string id)
{
Contract.Requires<ArgumentNullException>(id !=null);
prefix = (id.ToUpper())[];
int numLength = id.Length - ;
try
{
number = int.Parse(id.Substring(, numLength > ? : numLength));
}
catch(FormatException)
{
throw new EmployeeIdException("EmployeeId 格式错误!");
}
} /// <summary>
/// 重载Tostring()
/// </summary>
/// <returns></returns>
public override string ToString()
{
return prefix.ToString() + string.Format("{0,6:000000}",number);
} /// <summary>
/// 散列代码在整数取值区域上的分布相当均匀
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return (number ^ number << ) * 0x15051505;
} /// <summary>
/// 比较两个EmployeeId的值相同返回true
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(EmployeeId other)
{
if (other == null)
return false;
return (prefix == other.prefix && number == other.number);
} /// <summary>
/// 重载比较两个对象的值相同(重写object的Equal()方法)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return Equals((EmployeeId)obj);
} /// <summary>
/// 重载"=="运算符
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(EmployeeId left, EmployeeId right)
{
return left.Equals(right);
} /// <summary>
/// 重载"!="运算符
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(EmployeeId left, EmployeeId right)
{
return !(left == right);
}
}
}

值(Employee)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Dictionary
{
[Serializable]
public class Employee
{
private string name;
private decimal salary;
private readonly EmployeeId id; public Employee(EmployeeId id, string name, decimal salary)
{
this.id = id;
this.name = name;
this.salary = salary;
} /// <summary>
/// 重载字符串
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("{0} : {1,-20}{2:C}", id.ToString(), name, salary);
}
}
}

测试类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Dictionary
{
class Program
{
static void Main(string[] args)
{
var employees = new Dictionary<EmployeeId, Employee>();
var idTony = new EmployeeId("C3755");
var tony = new Employee(idTony, "Tony Stewart",379025.00m);
employees.Add(idTony,tony);
Console.WriteLine(tony); var idCar1 = new EmployeeId("F3547");
var car1 = new Employee(idCar1, "Car1 Edwards", 403466.00m);
employees.Add(idCar1,car1);
Console.WriteLine(car1); var idKevin = new EmployeeId("C3386");
var kevin = new Employee(idKevin, "Kevin Harwick", 415261.00m);
employees.Add(idKevin,kevin);
Console.WriteLine(kevin);
}
}
}

显示结果:

C#—集合(Collection)的更多相关文章

  1. Guava库介绍之集合(Collection)相关的API

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

  2. 【再探backbone 02】集合-Collection

    前言 昨天我们一起学习了backbone的model,我个人对backbone的熟悉程度提高了,但是也发现一个严重的问题!!! 我平时压根没有用到model这块的东西,事实上我只用到了view,所以昨 ...

  3. 5、数组和集合--Collection、Map

    一.数组:同一个类型数据的集合,其实他也是一个容器 1.数组的好处:可以自动给数组中的元素从0开始编号,方便操作这些数据 2.数组的定义: 在Java中常见: 格式1:  类型 [] 数组名 = ne ...

  4. WCF分布式开发步步为赢(8):使用数据集(DataSet)、数据表(DataTable)、集合(Collection)传递数据

    数据集(DataSet).数据表(DataTable).集合(Collection)概念是.NET FrameWork里提供数据类型,在应用程序编程过程中会经常使用其来作为数据的载体,属于ADO.NE ...

  5. 在含有null值的复杂类的集合(Collection)中取最大值

    在日常编程中,经常遇到要在一组复杂类的集合(Collection)中做比较.取最大值或最小值. 举个最简单的例子,我们要在一个如下结构的集合中选取包含最大值的元素: public class Clas ...

  6. 集合Collection总览

    前言 声明,本文使用的是JDK1.8 从今天开始正式去学习Java基础中最重要的东西--->集合 无论在开发中,在面试中这个知识点都是非常非常重要的,因此,我在此花费的时间也是很多,得参阅挺多的 ...

  7. java中集合Collection转list对象

    参考:java中集合Collection转list对象 首先我的需求是获取到购物车列表,购物车列表是一个Map对象,构造方法获取购物项,这里购物项是Collection对象 // 购物项集合,K商品I ...

  8. java基础27 单例集合Collection及其常用方法

    1.集合 集合是存储对象数据的集合容器 1.1.集合比数组的优势 1.集合可以存储任意类型的数据,数组只能存储同一种数据类型的数据    2.集合的长度是变化的,数组的长度是固定的 1.2.数组:存储 ...

  9. 18_java之集合Collection

    01集合使用的回顾 *A:集合使用的回顾 *a.ArrayList集合存储5个int类型元素 public static void main(String[] args) { ArrayList< ...

  10. 集合--Collection接口详解&&迭代器

    /* * 集合的顶层接口--Collection接口 * 添加 * add() * addAll() * * 遍历集合 * iterator() 迭代器 * * 删除 * remove() * rem ...

随机推荐

  1. 在uboot上创建菜单

    一.原理 菜单其实就是一个uboot中的命令,和其他的命令没有什么差别.  uboot启动时,如果进入uboot命令模式,先运行这个命令,就会打印出一个菜单界面. 在uboot的命令模式,通过键入“m ...

  2. Numpy基础笔记

    Numpy简介 Numpy(Numerical Python的简称)是高性能科学计算和数据分析的基础包.其部分功能如下: ①ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组 ...

  3. linux常用命令(4)rm命令

    rm是一个危险的命令,使用的时候要特别当心,尤其对于新手,否则整个系统就会毁在这个命令(比如在/(根目录)下执行rm * -rf).所以,我们在执行rm之前最好先确认一下在哪个目录,到底要删除什么东西 ...

  4. 如何完美打造Win8 Metro版IE10浏览器页面(转)

    Windows8 内置两种 Internet Explorer 10 (以下简称 IE10),一个是在桌面环境下使用的 IE10:视窗操作.可以支持各种插件(ActiveX):而另外一个则是在新的开始 ...

  5. go bufio

    1 bufio 读结构 type Reader struct {    buf          []byte     // 缓冲区    rd           io.Reader // read ...

  6. Eclipse控制台中文乱码

    换了OS真是,主要就是对Eclipse的配置操作不熟悉.用着不顺手.源文件一直都是按照google java style的做法保存为UTF-8.现在显示乱码,就得改Eclipse解码的配置为 UTF- ...

  7. shell command使用技巧

    1窗口可以merge 2.可以通过 control+t打开窗口

  8. 【转】Android--广播BroadcastReceiver

    原文网址:http://www.cnblogs.com/plokmju/p/android_broadcastreceiver.html 前言 Android四大组件,Activity.Service ...

  9. 数据结构(树链剖分,堆):HNOI 2016 network

    2215. [HNOI2016]网络 ★★★☆   输入文件:network_tenderRun.in   输出文件:network_tenderRun.out   简单对比时间限制:2 s   内存 ...

  10. 【图论】【宽搜】【染色】NCPC 2014 A Ades

    题目链接: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1787 题目大意: N个点M条无向边(N,M<=200000),一个节点只能有一个 ...