Export (0) Print
Expand All
3 out of 4 rated this helpful - Rate this topic

IDictionary Interface

Represents a nongeneric collection of key/value pairs.

Namespace:  System.Collections
Assembly:  mscorlib (in mscorlib.dll)
[ComVisibleAttribute(true)]
[DefaultMemberAttribute("Item")]
public interface IDictionary : ICollection, 
	IEnumerable

The IDictionary type exposes the following members.

  NameDescription
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360CountGets the number of elements contained in the ICollection. (Inherited from ICollection.)
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360IsFixedSizeGets a value indicating whether the IDictionary object has a fixed size.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360IsReadOnlyGets a value indicating whether the IDictionary object is read-only.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360IsSynchronizedGets a value indicating whether access to the ICollection is synchronized (thread safe). (Inherited from ICollection.)
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360ItemGets or sets the element with the specified key.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360KeysGets an ICollection object containing the keys of the IDictionary object.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360SyncRootGets an object that can be used to synchronize access to the ICollection. (Inherited from ICollection.)
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360ValuesGets an ICollection object containing the values in the IDictionary object.
Top
  NameDescription
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360AddAdds an element with the provided key and value to the IDictionary object.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360ClearRemoves all elements from the IDictionary object.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360ContainsDetermines whether the IDictionary object contains an element with the specified key.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360CopyToCopies the elements of the ICollection to an Array, starting at a particular Array index. (Inherited from ICollection.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360GetEnumerator()Returns an IDictionaryEnumerator object for the IDictionary object.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360GetEnumerator()Returns an enumerator that iterates through a collection. (Inherited from IEnumerable.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360RemoveRemoves the element with the specified key from the IDictionary object.
Top
  NameDescription
Public Extension MethodSupported by Silverlight for Windows PhoneAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodSupported by Silverlight for Windows PhoneSupported by Xbox 360Cast<TResult>Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodSupported by Silverlight for Windows PhoneSupported by Xbox 360OfType<TResult>Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top

The IDictionary interface is the base interface for nongeneric collections of key/value pairs. For the generic version of this interface, see System.Collections.Generic.IDictionary<TKey, TValue>.

Each element is a key/value pair stored in a DictionaryEntry object.

Each pair must have a unique key. Implementations can vary in whether they allow the key to be null. The value can be null and does not have to be unique. The IDictionary interface allows the contained keys and values to be enumerated, but it does not imply any particular sort order.

IDictionary implementations fall into three categories: read-only, fixed-size, variable-size. A read-only IDictionary object cannot be modified. A fixed-size IDictionary object does not allow the addition or removal of elements, but does allow the modification of existing elements. A variable-size IDictionary object allows the addition, removal, and modification of elements.

The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the IDictionary object is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. For example:

foreach (DictionaryEntry de in CastMembers) {...}

The foreach statement is a wrapper around the enumerator, which allows only reading from but not writing to the collection.

Notes to Implementers

The implementing class must have a means to compare keys.

The following code example demonstrates how to define a simple dictionary class that implements the IDictionary interface.


using System;
using System.Collections;

// This class implements a simple dictionary using an array of DictionaryEntry objects (key/value pairs).
public class SimpleDictionary : IDictionary
{
   // The array of items
   private DictionaryEntry[] items;
   private Int32 ItemsInUse = 0;

   // Construct the SimpleDictionary with the desired number of items.
   // The number of items cannot change for the life time of this SimpleDictionary.
   public SimpleDictionary(Int32 numItems)
   {
      items = new DictionaryEntry[numItems];
   }


   #region IDictionary Members
   public bool IsReadOnly { get { return false; } }
   public bool Contains(object key)
   {
      Int32 index;
      return TryGetIndexOfKey(key, out index);
   }
   public bool IsFixedSize { get { return false; } }
   public void Remove(object key)
   {
      if (key == null) throw new ArgumentNullException("key");
      // Try to find the key in the DictionaryEntry array
      Int32 index;
      if (TryGetIndexOfKey(key, out index))
      {
         // If the key is found, slide all the items up.
         Array.Copy(items, index + 1, items, index, ItemsInUse - index - 1);
         ItemsInUse--;
      }
      else
      {
         // If the key is not in the dictionary, just return. 
      }
   }
   public void Clear() { ItemsInUse = 0; }
   public void Add(object key, object value)
   {
      // Add the new key/value pair even if this key already exists in the dictionary.
      if (ItemsInUse == items.Length)
         throw new InvalidOperationException("The dictionary cannot hold any more items.");
      items[ItemsInUse++] = new DictionaryEntry(key, value);
   }
   public ICollection Keys
   {
      get
      {
         // Return an array where each item is a key.
         Object[] keys = new Object[ItemsInUse];
         for (Int32 n = 0; n < ItemsInUse; n++)
            keys[n] = items[n].Key;
         return keys;
      }
   }
   public ICollection Values
   {
      get
      {
         // Return an array where each item is a value.
         Object[] values = new Object[ItemsInUse];
         for (Int32 n = 0; n < ItemsInUse; n++)
            values[n] = items[n].Value;
         return values;
      }
   }
   public object this[object key]
   {
      get
      {
         // If this key is in the dictionary, return its value.
         Int32 index;
         if (TryGetIndexOfKey(key, out index))
         {
            // The key was found; return its value.
            return items[index].Value;
         }
         else
         {
            // The key was not found; return null.
            return null;
         }
      }

      set
      {
         // If this key is in the dictionary, change its value. 
         Int32 index;
         if (TryGetIndexOfKey(key, out index))
         {
            // The key was found; change its value.
            items[index].Value = value;
         }
         else
         {
            // This key is not in the dictionary; add this key/value pair.
            Add(key, value);
         }
      }
   }
   private Boolean TryGetIndexOfKey(Object key, out Int32 index)
   {
      for (index = 0; index < ItemsInUse; index++)
      {
         // If the key is found, return true (the index is also returned).
         if (items[index].Key.Equals(key)) return true;
      }

      // Key not found, return false (index should be ignored by the caller).
      return false;
   }
   private class SimpleDictionaryEnumerator : IDictionaryEnumerator
   {
      // A copy of the SimpleDictionary object's key/value pairs.
      DictionaryEntry[] items;
      Int32 index = -1;

      public SimpleDictionaryEnumerator(SimpleDictionary sd)
      {
         // Make a copy of the dictionary entries currently in the SimpleDictionary object.
         items = new DictionaryEntry[sd.Count];
         Array.Copy(sd.items, 0, items, 0, sd.Count);
      }

      // Return the current item.
      public Object Current { get { ValidateIndex(); return items[index]; } }

      // Return the current dictionary entry.
      public DictionaryEntry Entry
      {
         get { return (DictionaryEntry)Current; }
      }

      // Return the key of the current item.
      public Object Key { get { ValidateIndex(); return items[index].Key; } }

      // Return the value of the current item.
      public Object Value { get { ValidateIndex(); return items[index].Value; } }

      // Advance to the next item.
      public Boolean MoveNext()
      {
         if (index < items.Length - 1) { index++; return true; }
         return false;
      }

      // Validate the enumeration index and throw an exception if the index is out of range.
      private void ValidateIndex()
      {
         if (index < 0 || index >= items.Length)
            throw new InvalidOperationException("Enumerator is before or after the collection.");
      }

      // Reset the index to restart the enumeration.
      public void Reset()
      {
         index = -1;
      }
   }
   public IDictionaryEnumerator GetEnumerator()
   {
      // Construct and return an enumerator.
      return new SimpleDictionaryEnumerator(this);
   }
   #endregion

   #region ICollection Members
   public bool IsSynchronized { get { return false; } }
   public object SyncRoot { get { throw new NotImplementedException(); } }
   public int Count { get { return ItemsInUse; } }
   public void CopyTo(Array array, int index) { throw new NotImplementedException(); }
   #endregion

   #region IEnumerable Members
   IEnumerator IEnumerable.GetEnumerator()
   {
      // Construct and return an enumerator.
      return ((IDictionary)this).GetEnumerator();
   }
   #endregion
}

public sealed class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Create a dictionary that contains no more than three entries.
      IDictionary d = new SimpleDictionary(3);

      // Add three people and their ages to the dictionary.
      d.Add("Jeff", 40);
      d.Add("Kristin", 34);
      d.Add("Aidan", 1);

      outputBlock.Text += String.Format("Number of elements in dictionary = {0}", d.Count) + "\n";

      outputBlock.Text += String.Format("Does dictionary contain 'Jeff'? {0}", d.Contains("Jeff")) + "\n";
      outputBlock.Text += String.Format("Jeff's age is {0}", d["Jeff"]) + "\n";

      // Display every entry's key and value.
      foreach (DictionaryEntry de in d)
      {
         outputBlock.Text += String.Format("{0} is {1} years old.", de.Key, de.Value) + "\n";
      }

      // Remove an entry that exists.
      d.Remove("Jeff");

      // Remove an entry that does not exist, but do not throw an exception.
      d.Remove("Max");

      // Show the names (keys) of the people in the dictionary.
      foreach (String s in d.Keys)
         outputBlock.Text += s + "\n";

      // Show the ages (values) of the people in the dictionary.
      foreach (Int32 age in d.Values)
         outputBlock.Text += age + "\n";
   }
}

// This code produces the following output.
//
// Number of elements in dictionary = 3
// Does dictionary contain 'Jeff'? True
// Jeff's age is 40
// Jeff is 40 years old.
// Kristin is 34 years old.
// Aidan is 1 years old.
// Kristin
// Aidan
// 34
// 1


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.