c# SortedList的使用

来源:互联网 发布:ps合成照片软件 编辑:程序博客网 时间:2024/04/28 20:49

对IDictionary进行操作是,发现用SortedList也可以等同于 ArryList和Hashtable的结合,只是通过Key排序,key不允许为空和null

value可以,在效率上没有测试,但是保证是低,必定在插入时要比较排序。

 

通过公用方法得到信息(得到1行数据):

  1. public IDictionary ExecuteDictionary( IDbCommand iCmd )
  2.     {
  3.         IDataReader reader = null;
  4.         try
  5.         {
  6.             //只读取一行数据,第一行
  7.             reader = iCmd.ExecuteReader( CommandBehavior.SingleRow );
  8.         }
  9.         catch(Exception e)
  10.         {
  11.             this.Close( iCmd );
  12.             return null;
  13.         }
  14.         IDictionary dict = null;
  15.         if(reader.Read())
  16.         {
  17.             int fieldCount = reader.FieldCount;
  18.             dict = new SortedList( fieldCount );
  19.             for(int i = 0; i < fieldCount; i++)
  20.             {
  21.                 dict [reader.GetName( i ).ToLower()] = reader.GetValue( i );
  22.             }
  23.         }
  24.         reader.Close();
  25.         reader.Dispose();
  26.         return dict;
  27.     }

 

  1. //返回list 
  2. public SortedList selectSingln()
  3.     {
  4.         DB.CommandText = @"  SELECT TOP 5  *  FROM products";
  5.         DB.CommandType = CommandType.Text;
  6.         return (SortedList)DB.ExecuteDictionary();
  7.     }
  8. //遍历list
  9. private void _BeginRun()
  10.     {
  11.         _SqlServerLogic logic = new _SqlServerLogic();
  12.         SortedList dic = logic.selectSingln();
  13.         Hashtable hash = new Hashtable();
  14.         
  15.         //遍历sortlist
  16.         foreach(DictionaryEntry entry in dic)
  17.         {
  18.             Response.Write( entry.Key + "***" + entry.Value + "<br>" );
  19.             if(  !string.IsNullOrEmpty( entry.Value.ToString() ) )
  20.             {
  21.                 hash.Add( entry.Key, entry.Value );
  22.             }
  23.         }
  24.         IDictionaryEnumerator item = hash.GetEnumerator();
  25.         
  26.         //遍历Hashtable
  27.         while( item.MoveNext() )
  28.         { 
  29.             Response.Write( item.Key +"-----"+ item.Value +"<br/>" ); 
  30.         }
  31.         string [] ary = new string [dic.Count];
  32.         dic.Keys.CopyTo( ary, 0 );
  33.         Response.Write( string.Join( ",", ary ) );
  34.         //for 遍历list
  35.         for(int i = 0; i < dic.Count; i++)
  36.         {
  37.             Response.Write( dic.GetKey(i)+"----"+ dic.GetByIndex(i) +"<br/>" );
  38.         }
  39.     }

 

原创粉丝点击