---
title: "如何让.NET中的强类型的排序列表SortedList支持重复键"
author: "ericguo"
date: "2007-02-19T17:57:00Z"
tags: []
slug: "net-sortedlist"
draft: false
lastmod: "2007-02-19T17:57:00Z"
id: 56080
url: "https://ericguo.iteye.com/blog/56080"
---

非强类型的SortedList如何支持重复键可以参照Pharaoh在2005年就写的blog：《[不排序和可以重复key的SortedList](/Pharaoh/archive/2005/05/16/156202.html)》，强类型的SortedList同非强类型的一样可以支持重复键，并不像MSDN上所说的那样，“[In either case, a SortedList does not allow duplicate keys.](http://msdn2.microsoft.com/en-us/library/system.collections.sortedlist.aspx#remarksToggle)”。

比较非强类型的SortedList，强类型的SortedList需要综合应用C#泛型，接口，继承以及Singleton设计模式来实现，短短几十行代码还是很有点味道的，下面示例是一个允许DateTime键重复，按照DateTime先后顺序排序的一个事件队列的实现：

 1 internal class CEventListComparer : IComparer&lt;DateTime&gt;  
 2 {  
 3     static private CEventListComparer mono;  
 4     public static CEventListComparer EarlyFirst  
 5     {  
 6         get  
 7         {  
 8             if (mono == null)  
 9                 mono = new CEventListComparer();  
10             return mono;  
11         }  
12     }  
13   
14     #region IComparer  
15     public int Compare(DateTime x, DateTime y)  
16     {  
17         if (x == y)  
18             return -1;  
19         else if (x &lt; y)  
20             return -1;  
21         else  
22             return 1;  
23     }  
24     #endregion  
25 }  
26   
27 internal class CEventList : SortedList&lt;DateTime, IScheduleable&gt;  
28 {  
29     public CEventList() : base(CEventListComparer.EarlyFirst)  
30     {  
31     }  
32   
33     public IScheduleable PopEarlistSchedule(out DateTime newTime)  
34     {  
35         IScheduleable ish = null;  
36         IEnumerator&lt;KeyValuePair&lt;DateTime, IScheduleable&gt;&gt; getFirst = GetEnumerator();  
37         getFirst.MoveNext();  
38         newTime = getFirst.Current.Key;  
39         ish = getFirst.Current.Value;  
40         RemoveAt(0);  
41         return ish;  
42     }  
43   
44     internal void Schedule(DateTime ScheduledTime, IScheduleable ScheduledCall)  
45     {  
46         Add(ScheduledTime, ScheduledCall);  
47     }  
48 }

上面的事件队列(CEventList)正是我在编写的离散事件仿真程序的核心数据结构，是生产代码哦![](http://www.cnblogs.com/Emoticons/emwink.gif)

![](http://www.cnblogs.com/ericguo/aggbug/652775.html)

[丁丁](http://ericguo.cnblogs.com/) 2007-02-20 01:57 [发表评论](http://www.cnblogs.com/ericguo/archive/2007/02/20/generic_sortedlist_support_multikey.html#Feedback)