当前位置:编程学习 > C#/ASP.NET >>

keys可重复的字典

众所周知,C#Dictionary中的keys 是不允许重复的。以前在程序中使用了Dictionary,结果今天客户要求keys 可以重复。所以为了简单只好找个可重复的Dictionary-->SortedList:SortedList 对象包含用键/值对表示的项目。SortedList 对象可按照字符顺序或数字顺序自动地对项目进行排序。根据SortedList 对象排序的特性课巧妙的让它的key是可重复。代码如下:
 public class MySort : IComparer
        {
            public int Compare(object x, object y)
            {
                return -1;
 
            }
            
        }
 
 SortedList mySortedList = new SortedList(new MySort());
            mySortedList.Add(333, 333);
            mySortedList.Add(111, 111);
            mySortedList.Add(222, 222);
            mySortedList.Add(111, 112);
//遍历SortedList方法(1)
            for (int i = 0; i < mySortedList.Count; i++)
            {
                System.Console.WriteLine(mySortedList.GetKey(i));
                System.Console.WriteLine(mySortedList.GetByIndex(i));
            }
            System.Console.WriteLine("\n");
//遍历SortedList方法(2)
            foreach (DictionaryEntry de in mySortedList)
            {
                System.Console.WriteLine(de.Key);
                System.Console.WriteLine(de.Value);
            }
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,