- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace 集合
- {
- class 有序表
- {
- public static void Main()
- {
- //如果要用排好序的表,可以使用SortedList<TKey,TValue>来给元素排序
- SortedList<string , string > books = new SortedList<string,string>() ;
- books.Add( "aladdin" , "64kb@163.com" ) ;
- books.Add( "zhaohaifu" , "65kb@163.com" ) ;
- books.Add( "jacky" , "66kb@163.com" ) ;
- books.Add( "fuck" , "67kb@163.com" ) ;
- //键是不允许重复的,下面我们用Add方法重新添加一次aladdin
- //books.Add( "aladdin" , "sdaf" ) ; //刨出异常
- //但如果使用索引来赋值,如果键存在,则覆盖,如果不存在,相当于ADD添加。
- books[ "aladdin" ] = "haha_new" ;
- foreach( string str in books.Keys )
- {
- Console.WriteLine( str ) ;
- }
- foreach( string str in books.Values )
- {
- Console.WriteLine( str ) ;
- }
- //一次性遍历值键
- foreach( KeyValuePair<string,string> book in books )
- {
- Console.WriteLine( "名字:{0}邮箱:{1}" , book.Key , book.Value ) ;
- }
- //从上面结果可以看出,aladdin被替换了,他的值变成了haha_new
- //下面简单介绍一下SortedList<TKey,TValue>中的方法与属性
- //Capacity 这个属性用来设置与得到有序表的容量,与Ilist一样,也是成倍增长的
- //Comparer 返回与有序表相关的比较器,可以从构造中传入该比较器
- // Remove() RemoveAt() 按键删除与按索引删除
- // ContainsKey() ; ContainsValue() ; 检查是不是有包含指定值的键,或者值
- // TryGetValue() ; 尝试获得指定键的值,如果有就是true 并用out把值带回来,没有就是flase
- //按键删除
- Console.WriteLine( "-------------------------按键删除--------------" ) ;
- books.Remove( "aladdin" ) ;
- foreach( KeyValuePair<string,string> book in books )
- {
- Console.WriteLine( "名字:{0}邮箱:{1}" , book.Key , book.Value ) ;
- }
- //可以看出aladdin被删除了
- //下面我们按索引删除
- books.RemoveAt( 0 ) ;
- Console.WriteLine( "-------------------------按索引删除--------------" ) ;
- foreach( KeyValuePair<string,string> book in books )
- {
- Console.WriteLine( "名字:{0}邮箱:{1}" , book.Key , book.Value ) ;
- }
- //结果中看出fuck被删除,证明删除索引是以插入顺序为准,不是排序后的顺序。
- //检查是否包含aladdin 检查是否包含zhaohaifu (键)
- Console.WriteLine( "是否包含aladdin键:{0}" , books.ContainsKey( "aladdin" ) ) ; // false
- Console.WriteLine( "是否包含zhaohaifu键:{0}" , books.ContainsKey( "zhaohaifu" ) ) ; // true
- //检查是否包含64kb@163.com 检查是否包含64kb@163.com (值)
- Console.WriteLine( "是否包含aladdin键:{0}" , books.ContainsValue( "64kb@163.com" ) ) ; // false
- Console.WriteLine( "是否包含zhaohaifu键:{0}" , books.ContainsValue( "65kb@163.com" ) ) ; // true
- //此处的索引值是按排序后的顺序
- int keyindex = books.IndexOfKey( "zhaohaifu" ) ;
- Console.WriteLine( "zhaohaifu索引值:{0}" , keyindex ) ;
- string value = "" ;
- if( books.TryGetValue( "aladdin" , out value ))
- {
- Console.WriteLine( "得到了aladdin的值 :{0}" , value ) ;
- }
- string value2 = "" ;
- if( books.TryGetValue( "zhaohaifu" , out value2 ))
- {
- Console.WriteLine( "得到了zhoahaifu的值 :{0}" , value2 ) ;
- }
- Console.ReadLine() ;
- //注:本类是SortedList的泛型片,与之相对应的对象版的同名类存在,注意使用
- }
- }
- }
C# 中使用有序表SortedList
最新推荐文章于 2023-10-30 17:42:22 发布