您的位置:首页 > 编程语言 > C#

c# SortedList的使用

2008-11-18 10:19 239 查看
对IDictionary进行操作是,发现用SortedList也可以等同于 ArryList和Hashtable的结合,只是通过Key排序,key不允许为空和null

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

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

public IDictionary ExecuteDictionary( IDbCommand iCmd )

{

IDataReader reader = null;

try

{

//只读取一行数据,第一行

reader = iCmd.ExecuteReader( CommandBehavior.SingleRow );

}

catch(Exception e)

{

this.Close( iCmd );

return null;

}

IDictionary dict = null;

if(reader.Read())

{

int fieldCount = reader.FieldCount;

dict = new SortedList( fieldCount );

for(int i = 0; i < fieldCount; i++)

{

dict [reader.GetName( i ).ToLower()] = reader.GetValue( i );

}

}

reader.Close();

reader.Dispose();

return dict;

}

//返回list

public SortedList selectSingln()

{

DB.CommandText = @" SELECT TOP 5 * FROM products";

DB.CommandType = CommandType.Text;

return (SortedList)DB.ExecuteDictionary();

}

//遍历list

private void _BeginRun()

{

_SqlServerLogic logic = new _SqlServerLogic();

SortedList dic = logic.selectSingln();

Hashtable hash = new Hashtable();

//遍历sortlist

foreach(DictionaryEntry entry in dic)

{

Response.Write( entry.Key + "***" + entry.Value + "<br>" );

if( !string.IsNullOrEmpty( entry.Value.ToString() ) )

{

hash.Add( entry.Key, entry.Value );

}

}

IDictionaryEnumerator item = hash.GetEnumerator();

//遍历Hashtable

while( item.MoveNext() )

{

Response.Write( item.Key +"-----"+ item.Value +"<br/>" );

}

string [] ary = new string [dic.Count];

dic.Keys.CopyTo( ary, 0 );

Response.Write( string.Join( ",", ary ) );

//for 遍历list

for(int i = 0; i < dic.Count; i++)

{

Response.Write( dic.GetKey(i)+"----"+ dic.GetByIndex(i) +"<br/>" );

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: