C#—集合(Collection)

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 > 0)
            {
                Console.WriteLine(stack.Pop());
            }
            Console.WriteLine("Pop()出栈后栈中元素个数为:{0}", stack.Count);
        }
    }
}
View Code

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;
        }
    }

}
View Code

文档管理类

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 > 0;
            }
        }
    }
}
View Code

进程管理类

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)); //线程挂起事件小于20秒的随机数
            }

        }
    }
}
View Code

测试类

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 = 0; i < 10; i++)
            {
                var doc = new Document("Doc "+ i.ToString(),"content");
                dm.AddDocument(doc);
                Console.WriteLine("Added document {0}",doc.Title);
                Thread.Sleep(new Random().Next(20));
            }

        }
    }
}
View Code

显示结果

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;
        }
    }
}
View Code

文档管理(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>>(10);
            for (int i = 0; i < 10; 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 > 9 || priority<0)
            {
                throw new ArgumentException("优先级在1-9之间");
            }

            if (priorityNodes[priority].Value == null) 
            {
                --priority;
                if (priority >= 0)
                {
                    //判断下一个节点的优先级
                    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;
        }
    }
}
View Code

测试类

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",8));
            priorityDoc.AddDocument(new Document("two", "Sample", 5));
            priorityDoc.AddDocument(new Document("three", "Sample", 4));
            priorityDoc.AddDocument(new Document("four", "Sample", 8));
            priorityDoc.AddDocument(new Document("five", "Sample", 1));
            priorityDoc.AddDocument(new Document("six", "Sample", 9));
            priorityDoc.AddDocument(new Document("seven", "Sample", 1));
            priorityDoc.AddDocument(new Document("eight", "Sample", 1));

            priorityDoc.DisplayAllNodes();
        }
    }
}
View Code

显示结果:

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())[0];
            int numLength = id.Length - 1;
            try
            {
                number = int.Parse(id.Substring(1, numLength > 6 ? 6 : 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 << 16) * 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);
        }
    }
}
View Code

值(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);
        }
    }
}
View Code

测试类

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>(31);
            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);
        }
    }
}
View Code

显示结果:

原文地址:https://www.cnblogs.com/zxd543/p/3787949.html