NameObjectCollectionBase is the base class for a collection of associated String keys and Object values
using System;
using System.Collections;
using System.Collections.Specialized;
public class MyCollection : NameObjectCollectionBase
{
public MyCollection() {
}
public MyCollection( IDictionary d, Boolean bReadOnly ) {
foreach ( DictionaryEntry de in d ) {
this.BaseAdd( (String) de.Key, de.Value );
}
this.IsReadOnly = bReadOnly;
}
public DictionaryEntry this[ int index ] {
get {
return ( new DictionaryEntry(
this.BaseGetKey(index), this.BaseGet(index) ) );
}
}
public Object this[ String key ] {
get {
return( this.BaseGet( key ) );
}
set {
this.BaseSet( key, value );
}
}
public String[] AllKeys {
get {
return( this.BaseGetAllKeys() );
}
}
public Array AllValues {
get {
return( this.BaseGetAllValues() );
}
}
public String[] AllStringValues {
get {
return( (String[]) this.BaseGetAllValues( typeof( string ) ));
}
}
public Boolean HasKeys {
get {
return( this.BaseHasKeys() );
}
}
public void Add( String key, Object value ) {
this.BaseAdd( key, value );
}
public void Remove( String key ) {
this.BaseRemove( key );
}
public void Remove( int index ) {
this.BaseRemoveAt( index );
}
public void Clear() {
this.BaseClear();
}
}
public class SamplesNameObjectCollectionBase {
public static void Main() {
IDictionary d = new ListDictionary();
d.Add( "A", "a" );
d.Add( "B", "b" );
d.Add( "C", "c" );
MyCollection myROCol = new MyCollection( d, true );
myROCol.Add( "D", "d" );
PrintKeysAndValues( myROCol );
MyCollection myRWCol = new MyCollection();
myRWCol.Add( "Q", "q" );
PrintKeysAndValues( myRWCol );
myRWCol["o"] = "g";
PrintKeysAndValues( myRWCol );
myRWCol.Remove( "b" );
PrintKeysAndValues( myRWCol );
myRWCol.Clear();
PrintKeysAndValues( myRWCol );
}
public static void PrintKeysAndValues( MyCollection myCol ) {
for ( int i = 0; i < myCol.Count; i++ ) {
Console.WriteLine( "[{0}] : {1}, {2}", i, myCol[i].Key, myCol[i].Value );
}
}
public static void PrintKeysAndValues2( MyCollection myCol ) {
foreach ( String s in myCol.AllKeys ) {
Console.WriteLine( "{0}, {1}", s, myCol[s] );
}
}
}
Related examples in the same category