• 集合-有序列表


    有序列表:SortedList<TKey, TValue>,基于键对内容进行排序。对实例对象增加项时,用Add()方法添加,当key存在,则程序报异常;另一种添加项的方法是基于索引器,如果索引器存在,则更新value。

     var books = new SortedList<string, string>();
                books.Add("001", "张三与李四");
                books.Add("002", "十点钟开始");
                books.Add("004", "扒马褂");
                books["003"] = "宇宙牌香烟";
    
                //books.Add("001", "逗你玩"); //用这样的,则没办法更新。
                books["001"] = "逗你玩";//这样的既有添加又有更新Value的功能。
    
                foreach (KeyValuePair<string, string> book in books)//枚举器返回的类型KeyValuePair<TKey, TValue>
                {
                    Console.WriteLine("key:{0},value:{1}", book.Key, book.Value);
                }
    
                string title = "005";
                string content = " ";
                if (!books.TryGetValue(title, out content))
                {
                    Console.WriteLine("{0} not found!", title);
                }
                Console.Read();

    以上展现的是,默认的排序方式。我们可以在构造函数时传递自己希望的排序方式。如下按照长度排!

     class Program
        {
            static void Main(string[] args)
            {
                var books = new SortedList<string, string>(new MyCompare());
                books.Add("001", "张三与李四");
                books.Add("02", "十点钟开始");
                books.Add("004", "扒马褂");
                books["03"] = "宇宙牌香烟"; 
    
                foreach (KeyValuePair<string, string> book in books)//枚举器返回的类型KeyValuePair<TKey, TValue>
                {
                    Console.WriteLine("key:{0},value:{1}", book.Key, book.Value);
                } 
                Console.Read();
            }
        }
    
        public class MyCompare : IComparer<string>
        {
            public int Compare(string x, string y)
            {
                if (x.Length > y.Length)
                {
                    return 1;
                }
                return -1;
            }
        }
  • 相关阅读:
    五年磨一剑未成
    通过实例学习 VSL Hello World
    Web3d明日之星基于Javascript和OpenGL的技术
    将自己常去Web3D网站整理到文章中来
    FreeBSD,比较安静
    通过实例学习Virtools脚本语言VSL 合并字符串
    关于SQLite
    android中AsyncTask和Handler对比
    JavaScript中Array的prototype运用
    WampServer2.X 安装与使用说明
  • 原文地址:https://www.cnblogs.com/hometown/p/3208813.html
Copyright © 2020-2023  润新知